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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值