SYSK 211: Trace Only What You Want with TraceSource and SourceSwitch

With .NET 1.0 came the beloved System.Diagnostics.Trace and System.Diagnostics.TraceSwitch classes. While it provided the ability to filter out Trace.Write statements that did not meet the trace level setting of the TraceSwitch setting, it gave no ability to filter out tracing based on the module or class that invoked the tracing method.

 

Welcome to System.Diagnostics.TraceSource class. TraceSource class allows you, for example, to output trace messages for one class but not another. Why is it so useful? Consider a large enterprise application that has many modules, and many more classes. With TraceSource, you can now easily turn on tracing only for a part of the application.

 

Here is an example of doing that for a class Form1:

public partial class Form1 : Form

{

    static System.Diagnostics.TraceSource ts = null;

    public Form1()

    {

        ts = new System.Diagnostics.TraceSource(this.GetType().FullName);

                   

        // You can even automatically output callstack

        for (int i = 0; i < ts.Listeners.Count; i++)

        {

            ts.Listeners[i].TraceOutputOptions |= System.Diagnostics.TraceOptions.Callstack;

        }

        InitializeComponent();

    }

    [System.Diagnostics.Switch("WindowsApplication1.Form1.TraceLevelSwitch", typeof(System.Diagnostics.SourceSwitch))]

    private void button1_Click(object sender, EventArgs e)

    {

        ts.TraceEvent(System.Diagnostics.TraceEventType.Information, 1, "In button1_Click");

    }

}

 

 

The configuration file would be something like this:

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

      <system.diagnostics>

            <sources>

                  <source name="WindowsApplication1.Form1"

                        switchName="WindowsApplication1.Form1.TraceLevelSwitch"

                        switchType="System.Diagnostics.SourceSwitch" >

                  </source>

            </sources>

            <switches>

                  <!-- You can set the level at which tracing is to occur -->

                  <add name="WindowsApplication1.Form1.TraceLevelSwitch" value="Information" />

                  <!-- You can turn tracing off -->

                  <!--add name="WindowsApplication1.Form1.TraceLevelSwitch" value="Off" -->

            </switches>

      </system.diagnostics>

</configuration>