看了Modern C#系列课程5--C#中异常处理的笔记,主讲 俞晖
主要是跟踪(tracing),其实个人觉得,就是写一个写文件函数,把程序的每一步都写入文件,然后用DEBUG控制打开或关闭,效果一样。但是,这个跟踪好像要复杂一点。
首先,要增加一个配置文件。
在config中设定,打开/关闭tracing。
<configuration>
<appSettings>
<add key=”tracing” value=”true”/>
</appSettings>
</configuration>
可以通过在项目中添加配置文件,然后加上上面的语句。
然后,增加一个Globals.cs文件,读取配置文件中的配置信息。
using System;
using CFG = System.Configuration.ConfigurationSettings;//名字空间别名
namespace Tracing
{
public class Globals
{
public static readonly bool Trace;//全局变量,打开关闭跟踪的FLAG
static Globals() // constructor (called automatically upon first use of class)
{
try // to read trace setting
{
//通过读取配置文件中的KEY,取得相应的VALUE
Trace = System.Convert.ToBoolean( CFG.AppSettings["Tracing"] );
}
catch
{
Trace = false;
}
}
}//class
}//namespace
其次,在程序运行之前要做一些准备工作。在Form1.cs中:
static void Main()
{
//在当前目录生成AppLog.txt文件
string logfile = System.AppDomain.CurrentDomain.BaseDirectory + "AppLog.txt";
//打开一个IO流
System.IO.TextWriter log = new System.IO.StreamWriter(logfile);
//如果打开了跟踪
if (Globals.Trace) // then also send trace output to log file・
{
//生成一个跟踪的监听器
System.Diagnostics.TextWriterTraceListener logger;
//把跟踪的监听器绑定到IO流上
logger = new System.Diagnostics.TextWriterTraceListener(log);
//把监听器加入对象
System.Diagnostics.Trace.Listeners.Add(logger);
//跟踪对象写log,触发IO流写文件
System.Diagnostics.Trace.WriteLine("App starting: " + DateTime.Now);
}
//主程序运行
Application.Run(new Form1());
}
最后,在程序中需要写文件的地方加上跟踪对象的处理。
using System;
using T = System.Diagnostics.Trace; //名字空间别名
T.WriteLineIf(Globals.Trace, "DataAccess.Open():");
T.Indent(); //缩进
T.WriteLineIf(Globals.Trace, "Connection string=...");
T.Unindent();//取消缩进
T.Flush();//写完清空IO流
T.WriteLineIf(Globals.Trace, 参数);//参数可以是字符串或整形