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 下发现服务器线程启动也存在问题.很多 ...
随机推荐
- Markdown使用记录
1,打开Markdown文件夹(已经解压好了) 2,运行markdownPad2.exe. 3,然后工具-选项-程序语言 改为中文. 4,帮助-Markdown激活. 5,打开激活工具,KG_tt7z ...
- 性能测试-ApacheBench
基本简介 ApacheBench 是一个指令列程式,专门用来执行网站服务器的运行效能,特别是针对Apache 网站服务器.这原本是用来检测 Apache 网站服务器能够提供的效能,特别是可以看出Apa ...
- 消息队列与RabbitMQ
1 什么是消息队列 消息指进程或应用间通信的数据:队列是保存数据的结构:消息队列是指进程或应用间通信时,保存消息的容器.消息队列独特的机制和结构保证了消息发送者和接收者之间良好的异步通信. 2 为什么 ...
- [转]float,double和decimal类型
float:浮点型,含字节数为4,32bit,数值范围为-3.4E38~3.4E38(7个有效位) double:双精度实型,含字节数为8,64bit数值范围-1.7E308~1.7E308(15个有 ...
- HD2144Calculate S(n)
Problem Description Calculate S(n). S(n)=13+23 +33 +......+n3 . Input Each line will contain one int ...
- [原创]Devexpress XtraReports 系列 7 创建Drill-Down(向下钻取)报表
昨天发表了Devexpress XtraReports系列第六篇[原创]Devexpress XtraReports 系列 6 创建并排报表,今天我们继续. 今天的主题是创建Drill-Down报表. ...
- Unix 哲学
1.模块原则:使用简洁的接口拼接简单的部件 2.清晰原则:清晰胜于机巧 3.组合原则:设计时考虑拼接组合 4.分离原则:策略同机制分离,接口同引擎分离. 5.简洁原则:设计要简洁,复杂度能低则低 6. ...
- TCP三次握手及四次挥手详细图解(未完)
TCP是主机对主机层的传输控制协议,提供可靠的连接服务,采用三次握手确认建立一个连接: (完成三次握手,客户端与服务器开始传送数据) 所谓三次握手(Three-way Handshake),是指建立一 ...
- Android中使用gzip传递数据
HTTP协议上的GZIP编码是一种用来改进WEB应用程序性能的技术.大流量的WEB站点常常使用GZIP压缩技术来减少文件大小,减少文件大小有两个明显的好处,一是可以减少存储空间,二是通过网络传输文件时 ...
- CodeForces 709A Juicer (水题, 模拟)
题意:给定 n 个桔子的大小,一个杯子的容积,一个最大限度,挨着挤桔子汁,如果大小大于限度,扔掉,如果不杯子满了倒掉,问你要倒掉多少杯. 析:直接按要求模拟就好,满了就清空杯子. 代码如下: #pra ...