Monday, March 17, 2008

Sample of C# application tracing (class Trace).

To implement tracing in C# application it is suggested to use class Trace.

Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
TraceSwitch traceSwitch = new TraceSwitch("TraceLevelSwitch", "trace switch");

Trace.WriteLine("sample_Trace.Start");
for (int i = 0; i < 5; i++)
{
Trace.Indent();
Trace.WriteLineIf(traceSwitch.TraceInfo, "index: " + i + " indentLevel: " + Trace.IndentLevel);
Trace.Unindent();
}
Trace.WriteLine("sample_Trace.Finish");
VS Output window:

VS_output

Console screen:

console_output

Trace.Listeners allows to add additional trace target (in the sample, Console).

TraceSwitch helps to implement different levels of tracing.

When value of "TraceLevelSwitch" will be set "4" (see App.config file), then output will be next:

App.config file:

appConfigContent

VS Output window:

VS_output_traceLevel_4

Console screen:

console_output_traceLevel_4

Notes:

In Visual Studio 2005 projects, by default, the "DEBUG" conditional compilation symbol is defined for debug builds, and the "TRACE" symbol is defined for both debug and release builds. For information on how to disable this behavior, see the Visual Studio 2005 documentation.

Reference:

Trace Class

source of sample

App.config file

No comments: