Use Debug and Trace listeners in C#

[Debug]

By default, the Debug and Trace classes send messages to the Console window. Sometimes it might be nice to capture that text and save it in a file. This example shows how you can do that.

The Debug and Trace classes have a shared Listeners collection that contains listener objects. The classes actually send their message to those objects rather than directly to the Console window. Initially the Listeners collection contains a single listener that sends the text it receives to the Console window.

You can remove the default listener from the collection if you like, and you can add new listeners to the collection. This example uses the following code to add a TextWriterListener object that appends the text it receives to a text file.

// Make the listener.
private void Form1_Load(object sender, EventArgs e)
{
    string trace_file = Application.StartupPath + "//trace.txt";
    Trace.Listeners.Add(new TextWriterTraceListener(trace_file));
    Trace.AutoFlush = true;
}

The code composes a file name. It then creates a TextWriterTraceListener object, passing its constructor the file name, and adds the new listener to the Trace object’s Listeners collection. The Debug and Trace classes share the Listeners collection so this listener will write both Trace and Debug messages into the file.

By default, the Debug and Trace classes do not flush their text buffers into text files, so if the program ends without you explicitly flushing the output, some or all of the text may not be written into the file. The program avoids this problem by setting the Trace class’s AutoFlush property to true.

If you enter a message in the program’s TextBox and click Debug, the program executes the following code.

// Send a message to the Debug listeners.
private void btnDebug_Click(object sender, EventArgs e)
{
    Debug.WriteLine(txtMessage.Text);
    txtMessage.Clear();
    txtMessage.Focus();
}

This code uses the Debug.WriteLine method to send a message to the listeners. The default listener sends the text to the Console window and the other listener appends the text to the text file trace.txt.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in debugging and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *