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;               






    [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" ?>




                  <source name="WindowsApplication1.Form1"


                        switchType="System.Diagnostics.SourceSwitch" >                   




                  <!-- 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" -->






Comments (3)

  1. srinivas says:

    is this applicable for .net 2.0 or for 1.1 also

  2. irenake says:

    These classes are new in .NET 2.0

  3. matt dotson says:

    While your example is ok because of it’s single threaded nature, it should be considered TraceSource is NOT THREAD SAFE and probably should not be put in a static variable.  

Skip to main content