Wednesday, November 3, 2010

Adding a Text Writer Trace Listener via the Application Configuration File

When using the Trace class, a mechanism for recording messages that are sent to it are necessary. This is done by the use of listeners. The purpose of a listener is to collect store, and route tracing messages.

To send output to the listeners collection :

System.Diagnostics.Trace.WriteLine("Attempting to load form.");
The following example shows how to use a listener to send an output to a file:
System.Diagnostics.Trace.Listeners.Clear();
System.Diagnostics.Trace.Listeners.Add(
new System.Diagnostics.TextWriterTraceListener(@"C:\traceOutput.txt"));

The listener can also be configured by means of an application configuration file (App.config):

  <?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <system.diagnostics >                
      <trace autoflush="true" >
        <listeners>
          <clear />
            <add name="textWriterListener"
                 type="System.Diagnostics.TextWriterTraceListener"      
                 initializeData="C:\traceOutput.txt">      
            </add>           
        </listeners>                                 
      </trace >        
    </system.diagnostics>
  </configuration>

Exercise
1.       Create a new C# winforms application.
2.       Write a couple of trace statements in the form constructor.
   public SampleForm() {
System.Diagnostics.Trace.Write("Initializing Components...");
InitializeComponent();
System.Diagnostics.Trace.WriteLine("Done");
   }
3.       Add an application configuration file (app.config).
4.       Under configuration, add the following lines:
    <system.diagnostics >                   
      <trace autoflush="true" >
        <listeners>
          <clear />
            <add name="textWriterListener"
                 type="System.Diagnostics.TextWriterTraceListener"      
                 initializeData="C:\traceOutput.txt">           
          </add>       
        </listeners>                                     
      </trace >        
    </system.diagnostics>
5.       Run the application. The application will generate a C:\traceOutput.txt which contains the trace statements added in the form constructor.