Monday, May 2, 2005

Using Trace Switches in .Net

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/using_trace_switches_in_net.htm]

.Net has some great tracing features already built in. One of them is trace switches. You can create your own switches for each business process that needs tracing, such as trying to debug a tedious problem in the development environment. You can set switches in your config to various levels, and then call them from code. The trace levels (from MSDN) are:

Trace LevelConfiguration File Value
Off0
Error1
Warning2
Info3
Verbose4

You could set the following switches in your config. If the switch is omitted from the config file (and not instantiated elsewhere), then it is simply ignored.

<configuration>   
    <system.diagnostics
>
        <switches
>
            <add name="Security" value="4"
/>
            <add name="SubmitRequest" value="4"
/>
            <add name="ExternalMessages" value="0"
/>
        switches
>
    system.diagnostics
>

    <system.web
>
        ...
    system.web
>
configuration>

You could then instantiate the switch in code like so:

private System.Diagnostics.TraceSwitch mySwitch = new System.Diagnostics.TraceSwitch("Security","Login and Security");

Finally, you could access the various level by calling the Trace (i.e. "TraceVerbose") from the switch instance. This returns a bool if the level (from the app.config) is at or higher than . For example, TraceError is true if the Level is set to Error, Warning, Info, or Verbose; otherwise, it's false.

TraceSwitches provide an easy way for simple instrumentation of our business processes.

No comments:

Post a Comment