使用Trace实现程序日志

      在程序开发过程中,有时需要对程序运行状况做一些日志记录,以便以后查询,维护之用。
有时我们可以使用开源日志组件,如log4net,nlog,EntLib Log等,但有时为简便,
.netFramework中Trace,Debug就可以用来记录日志。并且也比较灵活。
位于System.Diagnostice名称空间下。注意,只有当程序集用TRACE和DEBUG符号常量编译是时,
这两个类才能正常工作。看代码:

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 #define TESTMODE  // #define directives must be at top of file
 2                            // Symbol names are uppercase by convention.
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 using System.Text;
 7 using System.IO;
 8 using System.Xml;
 9 using System.Xml.XPath;
10 using System.Diagnostics;
11 
12 namespace ConsoleTest1
13 {
14     public partial class TestTrace
15     {
16         [Conditional("DEBUG")]
17         /// <summary>
18         /// using Conditional Attributes
19         /// </summary>
20         public void TestTraceOutput()
21         {
22             Console.WriteLine("This string only display in DEBUG mode.");
23             //just for wait
24             Console.Read();
25         }
26 
27         /// <summary>
28         /// using Conditional Compilation
29         /// </summary>
30         /// <remarks>author PetterLiu http://wintersun.cnblogs.com </remarks>
31         public void TestTraceOutput2()
32         {
33 #if DEBUG
34             Console.WriteLine("This string only display in DEBUG mode.(using Conditional Compilation) ");
35             //just for wait
36             Console.Read();
37 #endif
38         }
39 
40         /// <summary>
41         /// using Conditional Compilation
42         /// </summary>
43         public void TestTraceOutput3()
44         {
45 #if TESTMODE
46             Console.WriteLine("This string only display define's TESTMODE mode.");
47             //just for wait
48             Console.Read();
49 #endif
50         }
51     }
52 }
53 
以上是一些简单应用,还可以使用TraceSource,TraceListener,

.net Framework中提供以下的TraceListener:
DefautTraceListener 默认的,数据流会重定向到Visual Studio的输出窗口

TextWriterTraceListener 以文件流或文件方式追加写到文件。

EventLogTraceListener 写Windows event log.

EventProviderTraceListener 写和追踪Windows (ETW) subsystem in Windows Vista.

WebPageTraceListener 写到一个ASP.NET web页面.

TextWriterTraceListener 子类又有
  ConsoleTraceListener   
  DelimitedListTraceListener
  XmlWriterTraceListener  
  EventSchemaTraceListener 将端对端事件的跟踪或调试输出定向到 XML 编码的符合架构的日志文件

注: EventSchemaTraceListener 是.net Framework 3.5 新增的。

本文主要演示TextWriterTraceListener,TraceOutputOptions可以记录当前时间,调用堆栈,进程信息等,
其它请参考MSDN。

ContractedBlock.gif ExpandedBlockStart.gif Code
 1         /// <summary>
 2         /// TextWriterTraceListener
 3         /// </summary>
 4         public void Foo()
 5         {
 6             Stream myFile = File.Create("TestFile.txt");
 7             TextWriterTraceListener twtl = new TextWriterTraceListener(myFile);
 8             Trace.Listeners.Add(new ConsoleTraceListener());
 9             Trace.Listeners.Add(twtl);
10             Trace.WriteLine("输出的内容");
11             Trace.Flush(); 
12         }
13 
14         /// <summary>
15         /// TraceSource and TraceListener
16         /// </summary>
17         public void TestTraceSource()
18         {
19             TraceSource ts1 = new TraceSource("Petter", SourceLevels.All);
20             TextWriterTraceListener txtlisten = new TextWriterTraceListener("RunningLog.txt");
21             //here can record current datetime and callstack information.
22             txtlisten.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.Callstack;
23             ts1.Listeners.Add(txtlisten);
24            
25             ts1.TraceData(TraceEventType.Information,11,"成功");
26             ts1.Flush();
27             ts1.Close();
28         }
同时增加,多个
ContractedBlock.gif ExpandedBlockStart.gif Code
 1         /// <summary>
 2         /// Add many Listeners.
 3         /// </summary>
 4         public void TestXMLTrace()
 5         {
 6             File.Delete("Escaped.xml");
 7             TraceSource ts2 = new TraceSource("TestSource2");
 8             ts2.Listeners.Add(new XmlWriterTraceListener("Escaped.xml"));
 9             ts2.Listeners.Add(new DelimitedListTraceListener("DelimitedLog.txt"));
10             // Set up a Windows Event log source and then create/add listener:
11             if (!EventLog.SourceExists("DemoApp"))
12                 EventLog.CreateEventSource("DemoApp""Application");
13 
14             ts2.Listeners.Add(new EventLogTraceListener("DemoApp"));
15 
16 
17             ts2.Switch.Level = SourceLevels.All;
18             ts2.TraceData(TraceEventType.Error, 38"message");
19 
20             ts2.Flush();
21             ts2.Close();
22         }       

注意:要调用Flush()方法后,才会把缓冲区内容写出去。cache只有4k,在Debug和Trace下使用任何文件流的listener,一个好的
策略是设置AutoFlush属性为True。否则,如果出一个未处理的异常或严重错误,最少4k缓存诊断信息可能会丢失。

使用配制文件,相关的选择项可在配制文件配制,推荐这种方法,比较灵活。
< configuration >
  
< system.diagnostics >
    
< trace  autoflush ="false"  indentsize ="4" >
      
< listeners >
        
< add  name ="myListener"
          type
="System.Diagnostics.TextWriterTraceListener"
          initializeData
="TextWriterOutput.log"   />
        
< remove  name ="Default"   />
      
</ listeners >
    
</ trace >
  
</ system.diagnostics >
</ configuration >

  后记,我们还可以根据需要继承TextWriterTraceListener,定义我们自己的TraceListener. http://wintersun.cnblogs.com
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值