C#: Using Trace Levels

To add levels of tracing into an application, that generate differing levels of output based on a setting in your applications config file, simply add a switch to the system.diagnostic node of your config file (create the system.diagnostics node if it doesn’t exist). Set the value of this switch to the level of trace required (0-4).

<configuration>
    <system.diagnostics>
        <switches>
            <add name="MyTraceSwitch" value="4" />
        </switches>
    </system.diagnostics>
</configuration>

To write trace output using that switch, simply create a TraceSwitch object that references the switch in your config file. Note that this will subsequently contain boolean properties that reflect your trace value specified in your config switch. Note that if your config file does not contain the reference switch, all of these values will be set to false (i.e. tracing will be turned off).
You can then simply perform a Trace.WriteLineIf based on these properties.

TraceSwitch traceSwitch = new TraceSwitch("MyTraceSwitch", "My Trace Switch");
Trace.WriteLineIf(traceSwitch.TraceError, "ERROR: hello world");
Trace.WriteLineIf(traceSwitch.TraceWarning, "WARNING: hello world");
Trace.WriteLineIf(traceSwitch.TraceInfo, "INFO: hello world");
Trace.WriteLineIf(traceSwitch.TraceVerbose, "VERBOSE: hello world");

To capture output, add a tracelistener or use software such as debugview.

You May Also Like

About the Author: rnowik

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.