The following three classes of System. Diagnostics can help us diagnose applications:
- Debug
- Trace
- EventLog
When creating a VS project, VS defines the Trace and Debug symbols for us. The difference between them is that the Trace is also valid in the release version, while the Debug is only valid in the Debug version. EventLog can be recorded in Windows system logs.
Trace and Debug use the same functions, but Trace is more powerful. By default, their output is the Console of the debugger.
Example (Basic API usage ):
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 ();
}
}
Trace can also be used with TraceSwitch to achieve the goal of configuring output by level. You can also use a custom 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>
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 );
}
}