引用地址:http://blog.csdn.net/aoshilang2249/article/details/41290047
TraceSource类的前身是Trace与Debug。在项目的实际使用过程中,一般通过以下步骤使用:
【1】定义配置文件.Config -- 配置TraceSource的源、控制级别、监听器等
- <?xml version="1.0" encoding="utf-8" ?>
- <configuration>
- <system.diagnostics>
- <!-- 跟踪的源 -->
- <sources>
- <source name="LogTrace" switchName="LogTraceSourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
- <listeners>
- <add name="textListener" />
- <remove name ="Default" />
- </listeners>
- </source>
- </sources>
- <!-- 控制跟踪输出 -->
- <switches>
- <!-- 侦听的全局级别, 对所有的侦听器有效 -->
- <add name="LogTraceSourceSwitch" value="Information" />
- <!-- 可以关闭全局侦听 -->
- <!--add name="LogTraceSourceSwitch" value="Off" -->
- </switches>
- <!-- 侦听器 -->
- <sharedListeners>
- <add name="textListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="trace.log">
- <!--设定特定侦听器的监听级别-->
- <filter type="System.Diagnostics.EventTypeFilter" initializeData="Warning" />
- </add>
- </sharedListeners>
- <!-- 侦听设置 -->
- <trace autoflush="true" indentsize="4" />
- </system.diagnostics>
- </configuration>
【2】定义TraceSource对象,可以简单封装
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- namespace LogTrace.Log
- {
- class CLog
- {
- public static void LogCritical(string strMessage)
- {
- _ts.TraceEvent(TraceEventType.Critical,
- 0,
- " [{0}{1}]: {2}",
- DateTime.Now.ToLongDateString(),
- DateTime.Now.ToLongTimeString(),
- strMessage);
- }
- public static void LogError(string strMessage)
- {
- _ts.TraceEvent(TraceEventType.Error,
- 0,
- " [{0}{1}]: {2}",
- DateTime.Now.ToLongDateString(),
- DateTime.Now.ToLongTimeString(),
- strMessage);
- }
- public static void LogWarning(string strMessage)
- {
- _ts.TraceEvent(TraceEventType.Warning,
- 0,
- " [{0}{1}]: {2}",
- DateTime.Now.ToLongDateString(),
- DateTime.Now.ToLongTimeString(),
- strMessage);
- }
- public static void LogInformation(string strMessage)
- {
- _ts.TraceEvent(TraceEventType.Information,
- 0,
- "[{0}{1}]: {2}",
- DateTime.Now.ToLongDateString(),
- DateTime.Now.ToLongTimeString(),
- strMessage);
- }
- private static TraceSource _ts = new TraceSource("LogTrace");
- }
- }
【4】编写测试代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using LogTrace.Log;
- namespace LogTrace
- {
- class Program
- {
- static void Main(string[] args)
- {
- CLog.LogCritical("Video Play()");
- CLog.LogError("Audio Play()");
- CLog.LogWarning("Picture Play()");
- CLog.LogInformation("SubTitle Play()");
- }
- }
- }