现在的位置: 首页 > 综合 > 正文

应用Trace类实现对程序的跟踪

2011年06月06日 ⁄ 综合 ⁄ 共 1685字 ⁄ 字号 评论关闭

我们写完一个程序以后,如果在客户那里出现了问题,由于环境不同找起来很麻烦,比较好的一个方法就是在程序里面写上日志,这样如果出问题的话,直接查看日志就可以了。

写日志当然有很多开源的东东,也可以自己来写。但是一是实现起来比较麻烦,二是需要一段时间来学习,三是可能会有潜在的问题。尤其是涉及到多线程的时候,潜在的问题就更多。

其实.net已经提供了现成的类,使用起来非常方便。它就是System.Diagnostics.Trace. 这个类提供了很多方便的方法,比如Write, WriteLine等等。这个类还支持输出目标的设置,可以使用系统内置提供的Listener,也可以自己写Listener.

我写了一个简单的例子,这个例子使用了Trace,Listener,更重要的是使用了多线程。

Program.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.Diagnostics;

 

namespace TraceSample

{


class
Program

{


static
void Main(string[] args)

{


ThreadStart threadDelegate = new
ThreadStart(Worker.Execute);

 


for (int i = 0; i < 5; i++)

{


Thread thread = new
Thread(threadDelegate);

thread.Name = String.Format("My Thread {0}", i );

thread.Start();

}

 

}

 

 

 

}

 


public
class
Worker

{


public
static
void Execute()

{


for (int i = 0; i < 500; i++)

{


Console.WriteLine("This is No. {0} task in No. {1} thread", i, System.Threading.Thread.CurrentThread.Name);


Trace.WriteLine(String.Format("This is No. {0} task in No. {1} thread",i, System.Threading.Thread.CurrentThread.Name), "Information");

}

}

}

 

 

}

 

App.config:

<?xml
version="1.0"
encoding="utf-8" ?>

<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>

 

输出结果截图:

从输出结果可以看出,该类对多线程支持良好。

这个例子很简单,这里只是想抛砖引玉,告诉大家以后记Log不用费尽心思自己写或者找开源的东东了,微软已经做好啦。

Trace类支持很多的输出方法,可以看这里

http://msdn.microsoft.com/zh-cn/library/system.diagnostics.trace_methods.aspx

如果想要记更详细的Log,可以使用EventLog类:

http://msdn.microsoft.com/zh-cn/library/system.diagnostics.eventlog.aspx

更多用于程序跟踪的类,在这里:

http://msdn.microsoft.com/zh-cn/library/gg145030.aspx

抱歉!评论已关闭.