Versatile Runtime Debug Output with Switches 
Jeff Key
January 20, 2002

Debug output outside of the debugger can significantly reduce the time maintaining applications, not to mention time saved during deployment.  As we all know, time is money, so time spent adding effective debug code early and often is a cost-saving measure you can't afford to dismiss as an annoyance.

The .NET framework gives us two classes that help us with this task:  BooleanSwitch and TraceSwitch.  These classes control flow of execution based on a value in the application's .config file; if the referenced setting is not in the .config file, the value is defaulted to "0".  The location of the elements necessary that control the switches is configuration/system.diagnostics/switches.1

<configuration>
    <system.diagnostics>
        <switches>< br>          <add name="TestSwitch" value="0" />
       </switches>
    </system.diagnostics>
</configuration>

Important:  Web applications handle their settings file differently than traditional apps.  Web apps reload their web.config file if it changes; traditional apps do not.  This is important to consider if you're using either of the Switch classes in a Windows Service, or other long-running application in that you will need to restart that application to have any changes made to its app.config file reflected.  Web applications recognize that a change has been made to its web.config file and reloads it during runtime, thus changes will be reflected immediately.

Note that the DEBUG or TRACE compiler options must be enabled.  DEBUG is defined in VisualStudio.NET's Debug configuration and TRACE is defined in both Debug and Release. 

The BooleanSwitch class 2
The BooleanSwitch class encapsulates a boolean variable whose value is changeable at run time.  Using the BooleanSwitch class is very easy: you create the object, passing in its name from the .config file and a description.  The "enabled" property returns true if the value is 1 or greater; false if 0 or the setting isn't there.

class TestBooleanSwitch
{
    private static BooleanSwitch output = new BooleanSwitch("TestSwitch", "My test switch");
    
    public static void Main()
    {
        if (output.Enabled)
            Console.WriteLine("BooleanSwitch is ON");
    }
}

The TraceSwitch class 3
The TraceSwitch is a bit more versatile, in that you have five levels you can use to determine the level of output desired.  This can be a great help in deployment/maintenance, as you can scale back expensive calls to the event log or other logging mechanism without having to recompile the application.

There are five levels supported by the TraceSwitch class (enumerated in the TraceLevel enum).  The higher levels imply the lower levels, so a Verbose setting will return true on a test for Info, Warning, etc.

Level Numeric Value
Off 0
Error 1
Warning 2
Info 3
Verbose 4

There are two approaches to using the TraceSwitch class:  You can test the Level property against one of the TraceLevels or test one of the level properties (TraceError, TraceInfo, etc.).

private TraceSwitch ts = new TraceSwitch("TestSwitch", "my test switch");
 
private void Test()
{
    if (ts.TraceVerbose) Log("Starting test");            
    try
    {
        int i = Convert.ToInt32("s");
    }
    catch (Exception ex)
    {
        if (ts.Level == TraceLevel.Error)
            Log("Error during test: " + ex.Message);
    }
}

Summary
The .NET framework makes life easier for us by providing a standard way to implement flow of execution directives and logging levels based on the standard .config file and a simple API.  Status reporting and remote debugging is a crucial element of enterprise development that people tend to gloss over until far too late in the development lifecycle.  Having a standard mechanism should encourage developers to write in these features while coding and not as an afterthought.  (Cross your fingers.)

Back to dotnet


  1. More information on the .config file settings at: ms-help://MS.VSCC/MS.MSDNVS/cpgenref/html/gngrftracedebugsettingsschema.htm
  2. Documentation at: ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemDiagnosticsBooleanSwitchClassTopic.htm
  3. Documentation at: ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfSystemDiagnosticsTraceSwitchClassTopic.htm