C#中使用跟踪侦听器TraceListener
修改App.config文件
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="0">
<listeners>
<add name="LogListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="LogConsoleApp.log"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
此时添加一个类型为System.Diagnostics.TextWriterTraceListener,它被设置为写入名为LogConsoleApp.log。还请注意,在节点,我们将设置autoflush属性为true。当设置为true此属性告诉侦听器在每次写操作后刷新缓冲区。实际应用程序,您可能希望将其设置为false限制磁盘读写操作。
记录器类
创建的记录器相当粗糙,因为我们没有记录错误的日期和时间,也没有记录源。因此,让我们通过创建一个小型记录器类来稍微扩展这个概念,如下所示
public class TraceHelper
{
private static TraceHelper _traceHelper;
private TraceHelper()
{
}
public static TraceHelper GetInstance()
{
if (_traceHelper == null)
_traceHelper = new TraceHelper();
return _traceHelper;
}
public void Error(string message, string module)
{
Log(message, MessageType.Error, module);
}
public void Error(Exception ex, string module)
{
Log(ex.StackTrace, MessageType.Error, module);
}
public void Warning(string message, string module)
{
Log(message, MessageType.Warning, module);
}
public void Info(string message, string module)
{
Log(message, MessageType.Information, module);
}
private void Log(string message, MessageType type, string module)
{
System.Diagnostics.Trace.WriteLine(
string.Format("{0},{1},{2},{3}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
type.ToString(),
module,
message));
}
}
public enum MessageType
{
Information = 0,
Warning = 1,
Error = 2
}
实际应用代码
var totalMoney1 = qry2.Where(a => a.name != "").Sum(a => a.total);
var totalMoney2 = qry2.Where(a => a.name == "").Sum(a => a.total);
TraceHelper.GetInstance().Info($"{ name } ,已收款总合计={totalMoney1},未收款总合计={totalMoney2}", "main");
记录文件
2020-09-18 10:16:32,Information,main,未知发票管理单位 ,已收款总合计=0 , 未收款总合计=2284771.71
2020-09-18 10:16:33,Information,main,发展公司 ,已收款总合计=822633 , 未收款总合计=211402
2020-09-18 10:16:33,Information,main,花市 ,已收款总合计=570000 , 未收款总合计=1543003.0
2020-09-18 10:16:34,Information,main,滘口联队 ,已收款总合计=0 , 未收款总合计=15000
2020-09-18 10:16:34,Information,main,九社 ,已收款总合计=0 , 未收款总合计=13500
2020-09-18 10:16:34,Information,main,三社 ,已收款总合计=0 , 未收款总合计=1872
2020-09-18 10:16:34,Information,main,十社 ,已收款总合计=0 , 未收款总合计=7800
2020-09-18 10:16:34,Information,main,十一社 ,已收款总合计=0 , 未收款总合计=9000
2020-09-18 10:16:34,Information,main,四社 ,已收款总合计=0 , 未收款总合计=1296390
2020-09-18 10:16:34,Information,main,五眼桥联社 ,已收款总合计=571916 , 未收款总合计=715843.0

本文介绍如何在C#中使用TextWriterTraceListener进行日志记录,并提供了一个实用的TraceHelper类,该类能够记录不同类型的日志消息。此外,还展示了如何在App.config文件中配置TraceListener,并给出了具体的日志记录实例。
3849

被折叠的 条评论
为什么被折叠?



