System.Diagnostics下面有三个类可以帮助我们诊断应用程序:
- Debug
- Trace
- EventLog
建立一个VS工程时,VS会为我们定义Trace和Debug这两个符号,它们的区别是Trace在release版本时也有效,而Debug只在Debug版本中有效。EventLog可以将日志记录到Windows的系统日志中.
Trace和Debug这两个类可以说用着相同的功能,只是Trace更强大些,默认情况下,它们的输出是调试器的Console。
示例(API的基本使用):
class Program
{
static TraceSwitch GlobalSwitch = new TraceSwitch("Test", "Test TraceSwitch");
static void Main(string[] args)
{
Trace.WriteLine("AutoFlush = " + Trace.AutoFlush.ToString());
Trace.WriteLine("My Trace Message");
Trace.WriteLine("My Trace Message", "Log1");
if (!Trace.AutoFlush)
{
Trace.Flush();
}
Trace.WriteLineIf(GlobalSwitch.Level >= TraceLevel.Warning, "If error or warning");
//Debug.WriteLine("AutoFlush=" + Debug.AutoFlush.ToString());
//Debug.WriteLine("My Debug Message");
//Debug.WriteLine("My Debug Message", "Log1");
Debug.WriteLineIf(DateTime.Now.Year > 2007, " today > 2007");
if (!Debug.AutoFlush)
{
Debug.Flush();
}
Console.ReadLine();
}
}
{
static TraceSwitch GlobalSwitch = new TraceSwitch("Test", "Test TraceSwitch");
static void Main(string[] args)
{
Trace.WriteLine("AutoFlush = " + Trace.AutoFlush.ToString());
Trace.WriteLine("My Trace Message");
Trace.WriteLine("My Trace Message", "Log1");
if (!Trace.AutoFlush)
{
Trace.Flush();
}
Trace.WriteLineIf(GlobalSwitch.Level >= TraceLevel.Warning, "If error or warning");
//Debug.WriteLine("AutoFlush=" + Debug.AutoFlush.ToString());
//Debug.WriteLine("My Debug Message");
//Debug.WriteLine("My Debug Message", "Log1");
Debug.WriteLineIf(DateTime.Now.Year > 2007, " today > 2007");
if (!Debug.AutoFlush)
{
Debug.Flush();
}
Console.ReadLine();
}
}
Trace还和TraceSwitch可以搭配使用,来达到按级别配置输出的目的。还可以使用自定义的Listener
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="0">
<listeners>
<add name="MyListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="MyListener.log"/>
<add name="MyListener2"
type="DiagnosticsApp.MyTraceListener, DiagnosticsApp"
/>
</listeners>
</trace>
<switches>
<add name="Test" value="4"/>
</switches>
</system.diagnostics>
</configuration>
<configuration>
<system.diagnostics>
<trace autoflush="true" indentsize="0">
<listeners>
<add name="MyListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="MyListener.log"/>
<add name="MyListener2"
type="DiagnosticsApp.MyTraceListener, DiagnosticsApp"
/>
</listeners>
</trace>
<switches>
<add name="Test" value="4"/>
</switches>
</system.diagnostics>
</configuration>
Trace.WriteLineIf(GlobalSwitch.Level >= TraceLevel.Warning, "If error or warning...");
public class MyTraceListener : System.Diagnostics.TraceListener
{
public override void Write(string message)
{
Console.Out.Write(message);
}
public override void WriteLine(string message)
{
Console.Out.WriteLine(message);
}
}
{
public override void Write(string message)
{
Console.Out.Write(message);
}
public override void WriteLine(string message)
{
Console.Out.WriteLine(message);
}
}