Thursday, March 11, 2004 - Posts

Using TraceSwitches

I've known about the TraceSwitch class for quite a while now.  However, I recently discovered how incredibly useful this really is.  I needed to create a Windows Service that invokes multiple threads of execution.  (When you have eight or ten processes executing simultaneously, you need LOTS of status information.)  In production, this information is not needed, and would waste a lot of space.  TraceSwitches provide a way to control the amount of log information that your application produces.

App.config
<configuration>
    
<system.diagnostics>
         
<switches>
              
<add name="General" value="4" />
         
</switches>
     </system.diagnostics>
</
configuration>

You define the switches in your app.config or web.config file.  The name will be used in your code to refer to the switch.  The value, which ranges from 0 to 4, indicates the level of logging you wish:

TraceLevel
0 = Off
1 = Error
2 = Warning
3 = Information
4 = Verbose

In your code, you create some switches, then use them to determine what to write:

Code
mySwitch = new TraceSwitch("General","Entire Application");
if (_Trace.TraceVerbose) { // write very wordy message }
if (_Trace.TraceInfo) { // write less wordy message }
if (_Trace.Warning) { // write warning message }
if (_Trace.Error) { // write error message }

Now I can easily vary my log output from EXTREMELY detailed to very sparse.  This has been a lifesaver.