Trace、Debug和TraceSource的使用以及日志设计 .
- Trace 和 Debug区别
- 什么是Listeners
- 跟踪开关
- 使用BooleanSwitch开关
- 使用TraceSwitch开关
- 使用TraceSource代替Trace和Debug
- 设计一个日志系统
- 关于EventLog
本章概要:
1:Trace 和 Debug区别
2:什么是Listeners
3:跟踪开关
3.1:使用BooleanSwitch开关
3.2:使用TraceSwitch开关
4:使用TraceSource代替Trace和
5:设计一个日志系统
6:关于EventLog
.NET Framework 命名空间 System.Diagnostics 包含用于跟踪执行流程的 Trace、Debug 和 TraceSource 类,以及用于分析代码的 Process、EventLog 和 PerformanceCounter 类。
跟踪是一种在应用程序运行时监视其执行情况的方式。当开发 .NET Framework 应用程序时,可以在其中添加跟踪和调试检测功能,并且在开发应用程序时和部署应用程序后,都可以使用该检测功能。利用 Trace 和 Debug 类,可以将有关错误和应用程序执行的信息记录到日志、文本文件或其他设备中,以便在随后进行分析。
下面列出了六个写入跟踪信息的 Debug Members 和 Trace 方法。
Assert:指定的文本;如果未指定任何文本,则为“调用堆栈”。只有当 Assert 语句中以参数形式指定的条件为 false 时,才会写入输出。
Fail:指定的文本;如果未指定任何文本,则为“调用堆栈”。
Write:指定的文本。
WriteIf:如果满足 WriteIf 语句中以参数形式指定的条件,则为指定的文本。
WriteLine:指定的文本和一个回车。
WriteLineIf:如果满足 WriteLineIf 语句中以参数形式指定的条件,则为指定的文本和一个回车。
1:Trace 和 Debug区别
Trace 和 Debug 类基本相同,不同的只是 Trace 类的过程和函数默认为编译成发布版本。
2:什么是Listeners
Listenters属性,它是TraceListenerCollection类型(TraceSource类和TraceListener类),给类属性控制跟踪信息输出的方向,可以是控制台(add(TextWriterTraceListener(new Console.Out))),文件(add(TextWriterTraceListener(new IO.File.CreateText(“output.txt”))等。Listenters集合中的成员包括TextWriterTraceListener,DefaultTraceListener,EventLogTraceListener,WebPageTraceListener等。而TextWriterTraceListener的子类又有ConsoleTraceListener, DelimitedListTraceListener,XmlWriterTraceListener,EventSchemaTraceListener。
您可以通过实现您自己的侦听器来生成自定义的结果。 所有自定义侦听器都应支持文章开头表中的六个方法。
以下的例子说明输出的消息将会在控制台、TXT文件以及系统日志中均被记录。
TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);
TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("output.txt"));
Debug.Listeners.Add(tr2);
EventLogTraceListener tr3 = new EventLogTraceListener();
Debug.Listeners.Add(tr3);
3:跟踪开关
除了指定Listener外,要控制消息是否被输出,还需要指定跟踪开关。跟踪开关用于启用、禁用和筛选跟踪输出。
Framework 中提供了三种类型的跟踪开关:BooleanSwitch 类、TraceSwitch 类和 SourceSwitch 类。BooleanSwitch是最简单的跟踪开关,可以指定是否输出消息。TraceSwitch 和 SourceSwitch 类用于为特定的跟踪级别启用跟踪开关,以便显示为该级别及其下的所有级别指定的 Trace 或 TraceSource 消息。
3.1:使用BooleanSwitch开关
以下是使用BooleanSwitch的例子:
TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);
TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("output.txt"));
Debug.Listeners.Add(tr2);
EventLogTraceListener tr3 = new EventLogTraceListener();
Debug.Listeners.Add(tr3); bool someBizCondition = true;
BooleanSwitch bs = new BooleanSwitch("DataMessageSwitch", "DataMessageSwitch des");
bs.Enabled = true;
Debug.WriteLineIf(someBizCondition, "log....");
Debug.Flush();
bs.Enabled设置为true或者false,并不会使程序自动决定是否输出信息。
如果不使用代码方式,而是使用配置文件的方式,是在 <configuration> 标记之后,但在 </configuration> 标记之前添加相应的 XML 来配置您的开关。如下:
<system.diagnostics>
<switches>
<add name="DataMessagesSwitch" value="1" />
</switches>
</system.diagnostics>
3.2:使用TraceSwitch开关
TraceSwitch类可以通过使用跟踪开关来筛选消息,通过Level属性来获取或设置开关级别。0、1、2、3 和 4 分别对应于 Off、Error、Warning、Info 和 Verbose。任何大于 4 的数字都会被当作 Verbose,任何小于零的数字都会被当作 Off。
以下的例子,用代码的方式来演示使用TraceSwitch来设置跟踪开关:
TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);
TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("output.txt"));
Debug.Listeners.Add(tr2);
EventLogTraceListener tr3 = new EventLogTraceListener();
Debug.Listeners.Add(tr3); bool someBizCondition = true;
TraceSwitch ts = new TraceSwitch("mySwitch", "in the Config file");
ts.Level = TraceLevel.Verbose;
Debug.WriteLineIf(ts.TraceError && someBizCondition, "Error!!!");
Debug.WriteLineIf(ts.TraceWarning && someBizCondition, "Warning!!!");
Debug.WriteLineIf(ts.TraceInfo && someBizCondition, "Info!!!");
Debug.WriteLineIf(ts.TraceVerbose && someBizCondition, "Verbose!!!");
Debug.Flush();
使用XML来配置,如下:
<system.diagnostics>
<switches>
<add name="mySwitch" value="1" />
</switches>
</system.diagnostics>
4:使用TraceSource代替Trace和Debug
从FRAMEWORK2.0开始,就不建议使用Trace和Debug了,而改而用TraceSouce。TraceSource 旨在用作增强的跟踪系统,并且可代替较旧的 Trace 和 Debug 跟踪类的静态方法使用。熟悉的 Trace 和 Debug 类仍然存在,不过建议的做法是使用 TraceSource 类进行跟踪。
下面的例子演示使用代码来实现消息的输出:
private static TraceSource mySource = new TraceSource("TraceSourceApp");
static void Main(string[] args)
{
mySource.Switch = new SourceSwitch("sourceSwitch", "Error");
mySource.Listeners.Remove("Default");
TextWriterTraceListener textListener = new TextWriterTraceListener("myListener.log");
textListener.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.Callstack;
textListener.Filter = new EventTypeFilter(SourceLevels.Error);
mySource.Listeners.Add(textListener);
ConsoleTraceListener console = new ConsoleTraceListener(false);
console.Filter = new EventTypeFilter(SourceLevels.Information);
console.Name = "console";
mySource.Listeners.Add(console);
Activity1();
// Set the filter settings for the
// console trace listener.
mySource.Listeners["console"].Filter = new EventTypeFilter(SourceLevels.Critical);
Activity2();
// Allow the trace source to send messages to
// listeners for all event types.
mySource.Switch.Level = SourceLevels.All;
// Change the filter settings for the console trace listener.
mySource.Listeners["console"].Filter = new EventTypeFilter(SourceLevels.Information);
Activity3();
mySource.Close();
return;
}
static void Activity1()
{
mySource.TraceEvent(TraceEventType.Error, 1, "Error message.");
mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.");
}
static void Activity2()
{
mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.");
mySource.TraceInformation("Informational message.");
}
static void Activity3()
{
mySource.TraceEvent(TraceEventType.Error, 4, "Error message.");
mySource.TraceInformation("Informational message.");
}
以上代码,如果使用配置文件的方式实现,如下:
<system.diagnostics>
<sources>
<source name="TraceSourceApp" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
<listeners>
<add name="console" type="System.Diagnostics.ConsoleTraceListener">
<filter type="System.Diagnostics.EventTypeFilter" initializeData="Warning"/>
</add>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="myListener.log"
traceOutputOptions="Callstack">
<filter type="System.Diagnostics.EventTypeFilter" initializeData="Error"></filter>
</add>
<remove name="Default"/>
</listeners>
</source>
</sources>
<switches>
<add name="sourceSwitch" value="Warning"/>
</switches>
</system.diagnostics>
配置文件实现的对应代码部分为:
private static TraceSource mySource = new TraceSource("TraceSourceApp");
static void Main(string[] args)
{
Activity1();
Activity2();
Activity3();
mySource.Close();
return;
}
static void Activity1()
{
mySource.TraceEvent(TraceEventType.Error, 1, "Error message.");
mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.");
}
static void Activity2()
{
mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.");
mySource.TraceInformation("Informational message.");
}
static void Activity3()
{
mySource.TraceEvent(TraceEventType.Error, 4, "Error message.");
mySource.TraceInformation("Informational message.");
}
5:设计一个日志系统
有了以上的知识之后,我们就可以来设计一个应用程序的日志系统(是的,我们不在需要LOG4NET)。我们来假设这个日志系统最基础的功能:
1、以日期来创建日志名,以免历史日志全部写入一个文件中去;
2、可以配置想要输出的日志类别,如Warning或者Error等;
3、可以配置想要的日志内容:如StackTrace或者错误信息等;
思路:
1、在应用程序启动代码中,设置文件名。因为文件名要根据日期动态生成,所以不能使用配置文件;
2、其它配置可以配置文件实现;
3、DO IT;
6:关于EventLog
关于EventLog是一个我不喜欢的功能,更多内容,可参考:http://msdn.microsoft.com/zh-cn/library/aaaxk5bx(VS.80).aspx
练习:
1.You are using the Microsoft Visual Studio 2005 IDE to examine the output of a method that returns a string.
You assign the output of the method to a string variable named fName. You need to write a code segment that
prints the following on a single line The message. "Test Failed. " The value of fName if the value of fName does
not equal "John" You also need to ensure that the code segment simultaneously facilitates uninterrupted execution
of the application. Which code segment should you use?
A. Debug.Assert(fName == "John", "Test FaileD. ", fName);
B. Debug.WriteLineIf(fName != "John", fName, "Test Failed");
C. if (fName != "John") {Debug.Print("Test FaileD. "); Debug.Print(fName); }
D. if (fName != "John") {Debug.WriteLine("Test FaileD. "); Debug.WriteLine(fName); }
Answer: B
17.You are testing a newly developed method named PersistToDB. This method accepts a parameter of type
EventLogEntry. This method does not return a value. You need to create a code segment that helps you to test the
method. The code segment must read entries from the application log of local computers and then pass the entries
on to the PersistToDB method. The code block must pass only events of type Error or Warning from the source
MySource to the PersistToDB method. Which code segment should you use?
A. EventLog myLog = new EventLog("Application", ".");
foreach (EventLogEntry entry in myLog.Entries)
{if (entry.Source == "MySource") { PersistToDB(entry); } }
B. EventLog myLog = new EventLog("Application", ".");
myLog.Source = "MySource";
foreach (EventLogEntry entry in myLog.Entries) {
if (entry.EntryType == (EventLogEntryType.Error & EventLogEntryType.Warning))
{ PersistToDB(entry); }}
C. EventLog myLog = new EventLog("Application", ".");
foreach (EventLogEntry entry in myLog.Entries)
{ if (entry.Source == "MySource")
{if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning)
{PersistToDB(entry); } } }
D. EventLog myLog = new EventLog("Application", ".");
myLog.Source = "MySource";
foreach (EventLogEntry entry in myLog.Entries)
{if (entry.EntryType == EventLogEntryType.Error || entry.EntryType == EventLogEntryType.Warning)
{PersistToDB(entry); }
Answer: C
Trace、Debug和TraceSource的使用以及日志设计 .的更多相关文章
- C#学习笔记14——TRACE、DEBUG和TRACESOURCE的使用以及日志设计
Trace.Debug和TraceSource的使用以及日志设计 .NET Framework 命名空间 System.Diagnostics 包含用于跟踪执行流程的 Trace.Debug 和 ...
- 【转】 C#学习笔记14——Trace、Debug和TraceSource的使用以及日志设计
[转] C#学习笔记14——Trace.Debug和TraceSource的使用以及日志设计 Trace.Debug和TraceSource的使用以及日志设计 .NET Framework 命名空 ...
- C# trace debug TraceListener调试信息详解
在C#编程中,可能要碰到把调试信息输出的问题,我们可以自己把信息显示在某个控件上,但是MS自己提供了一套机制帮助我们输出一些调试信息,这些信息有助于我们判断程序的走向,不用自己再去额外写调试代码了. ...
- 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗? 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现! 是否有一个全局视角来查看系统的运行状况? 有什么办法可以监控到JVM的实时运行状态?
https://alibaba.github.io/arthas/ Arthas 是Alibaba开源的Java诊断工具,深受开发者喜爱. 当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决 ...
- Nginx 配置日志路径(nginx.conf没有写log路径,所以debug的时候找不到日志)
缘由:nginx.conf没有写log路径,所以debug的时候找不到日志,遂在conf文件里写入了log路径 Setp1.nginx默认日志路径: /var/log/nginx Setp2.conf ...
- golang web框架设计4:日志设计
beego的日志设计思路来自于seelog,根据不同的level来记录日志,beego设计的日志是一个轻量级的,采用系统log.Logger接口,默认输出到os.Stdout,用户可以实现这个接口然后 ...
- angular代码分析之异常日志设计
angular代码分析之异常日志设计 错误异常是面向对象开发中的记录提示程序执行问题的一种重要机制,在程序执行发生问题的条件下,异常会在中断程序执行,同时会沿着代码的执行路径一步一步的向上抛出异常,最 ...
- 怎样启动JDBC Debug模式,打印JDBC诊断日志
1.下载Debug版本号jar包 首先要下载一个Debug版本号的JDBC jar包,Debug版本号的jar包命名形式为jdbcX_g.jar(例如以下图所看到的).如Oracle11g的 ...
- java war包 远程debug出现的问题解决,学会查看日志
开启远程debug之后,8005 关闭tomcat 又启动不了了.. netstat -lnp 未发现8005接口 eclipse 内远程链接到服务器,debug 下发现服务器线程启动也存在问题.很多 ...
随机推荐
- Maven依赖
可传递的依赖: 1.具体调用哪个版本?最短依赖长度的那个 如:A -> B -> C -> D 2.0 , A -> E -> D 1.0,那么调用D 1.0 为了避免这 ...
- make subversion时出现neon报错 及 svn其他问题汇总(3ge )
在make subvision时,出现以下错误提示: /usr/local/src/neon-0.29.6/src/ne_auth.c:781: undefined reference to`ne__ ...
- LeetCode(8) - String to Integer (atoi)
虽然是easy,却是比较繁琐的一道题,需要考虑各种边界条件.在WA了好几遍之后,才把各种边界条件给补全.需要考虑到的因素如下: 输入不合法字符,非"0-9",对于首位,合法字符还包 ...
- linux下使用libiconv库转码
iconv命令实现linux下字符集编码的转换 windows下的文件复制到linux下时常会乱码,因为windows下文件编码为GBK,linux下默认文件编码为UTF-8,故需要libiconv库 ...
- 第三百五十六天 how can I 坚持
一年了,三百五十六天.写个算法算下对不对. 今天突然想买辆自行车了.云马智行车,还是捷安特,好想买一辆. 网好卡.貌似少记了一天呢,357了.好快. 睡觉了,还没锻炼呢,太晚了. 1458748800 ...
- cocos2d-x 3.2 例子文件工程的位置
更新到3.2后突然想要看看官方的例子,忽然发现在test中的cpp工程下面没有了工程的启动配置.奇怪,难道只有代码吗?重新查找后原来启动的工程文件都移动到了build文件夹下面,具体的路径就是 coc ...
- centos安装lxml和pyspider
yum -y install --nogpgcheck python34u-devel.x86_64 yum -y install libcurl-devel yum -y install libxs ...
- 为何j2ee变成了javaee?
Sun的版本命名有点乱,Java刚面世时还貌不惊人,直到1.2出现后进步很大,Sun就叫它Java 2了,这个称谓持续到1.4,因此Java的三个平台对应的是J2ME(Java 2 Mobile Ed ...
- Session和Cookie的分析与区别
首先说一下Web.config文件中的cookieless="false"的理解 cookieless="false"表示: 如果用户浏览器支持cookie时启 ...
- HDU 5794 A Simple Chess (Lucas + dp)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5794 多校这题转化一下模型跟cf560E基本一样,可以先做cf上的这个题. 题目让你求一个棋子开始在( ...