Share via


Trace and Debug Classes

Fortunately, you do not have to step through an application line by line to figure out what is happening. The Systems.Diagnostics namespace includes Trace and Debug classes. These two classes (which are essentially identical) include a number of static methods that can be used to cause your code to gather information about code-execution paths, code coverage, and even performance profiling. Both classes also provide an Assert method that checks for a condition and displays a message if the condition is false.

To use the Trace and Debug classes, perform the following three steps.

  1. Define the TRACE or DEBUG symbol.
  2. Create a new instance of the corresponding Listener.
  3. Add calls to the Trace or Debug class to your code.

Define — To enable debugging or tracing, you must first define the corresponding symbol. This can be done at compile time using the /d(efine) conditional compilation switch for Visual C# (and the Managed Extensions for C++) or for Visual Basic .NET, as shown here:

csc /target:library /debug+ /d:TRACE math.cs
vbc /target:library /debug+ /d:TRACE=True math.vb

The symbol can also be defined in the source code itself, as shown here:

#define TRACE     // for C# or the Managed Extensions for C++
#Const TRACE=1    ' for Visual Basic .NET

Create — Both Debug and Trace output are captured by a TraceListener. By default, output is automatically sent to the DefaultTraceListener, which sends output to the Windows system debugger using the OutputDebugString Windows API and to the debugger using the Debugger.Log method. Messages sent using Debugger.Log have no effect if there is no debugger attached.

If you are operating inside the Windows-based debugger, the Output window will show Debug and Trace messages. However, if you are running outside the debugger — for example, on a tester's computer — or if you want to save debugging information to a text-based log file, you must create a new Listener and add it to the Listeners collection. The System.Diagnostic namespace provides an EventLogTraceListener and a TextWriterTraceListener. Creating a text file to handle debugging messages requires only the following single line of code.

Trace.Listeners.Add(new 
   TextWriterTraceListener(File.Create("output.txt")));

Add — Lastly, you can add calls to the various Trace.Write methods to generate debugging information at run time, as shown here:

Trace.WriteLine("");
Trace.WriteLine("Starting tracing...");

Because the first few bytes of the output file contain information about the text encoding of the file and are not readable, you might want to start logging on a new line, by first executing an empty WriteLine method.

The next thing to notice is the call to Trace.Indent, which by default indents the output by four spaces:

Trace.Indent();

Subsequent calls to Trace.Unindent will justify the output back towards the left.

This sample program also uses the WriteLineIf method of Trace to generate a logging message, but only if a certain condition is not met. In this particular case, the code anticipates that the first numeric entry will begin with a digit other than zero. If that test fails, a message is written, as shown in the following line.

Trace.WriteLineIf(test == "0", "Oops: Leading zero"); // C#
Trace.WriteLineIf(test = "0", "Oops: Leading zero")   ' VB

Putting all this together, executing the sample program creates the following Output.txt file.

Starting Tracing...
    InitializeComponent()
        Creating controls
        Setting up Label and TextBox
        Setting up numeric buttons
        Setting up operations buttons
        Adding Clear and Calculate
        Adding to Controls collection
    9 Clicked
    - Clicked
    6 Clicked
    Calculate Clicked
Dispose()

The Assert method operates in a similar fashion, except that the output is in the form of a detailed error dialog, and the test fails. The corresponding Assert method looks like the following code.

Trace.Assert(test != "0", "Oops", "Leading zero"); // C#
Trace.Assert(test <> "0", "Oops", "Leading zero")  ' Visual Basic .NET

When Calc.exe is run and the user enters a leading zero, the following dialog box is produced.

**Note   **If your program fails to run to completion, a 0-byte Output.txt file will be produced.

See Also

Debugging and Optimization | The Microsoft CLR Debugger | Debugging ASP.NET Web Applications | Appendix A: For Additional Information | Appendix B: Runtime Debugger (CorDbg.exe)