C#使用跟踪侦听器TraceListener
- 修改App.config文件
- 记录器类
- 实际应用代码
- 记录文件
修改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