If you’ve never used Tracing in your .NET applications, it can be tricky remembering the steps. I present the following snippet as a quick guide to get you on your way.
Firstly, add a switch to your App.Config file. The name can be anything, and you can add as many switches as you need. For example, each switch could represent a different sub-system within your application:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.diagnostics> <switches> <add name="MySwitch" value="0" /> </switches> </system.diagnostics> </configuration>
Note the value is set to zero, we’ll come back to that. Next, create a FileStream to write the log file. I’ve set the FileMode to Create so we start a new log each time the program is run. Change this to FileMode.Append if you need to build the log up over several runs. By default, the file will be created in the same folder as the application’s exe file.
FileStream fs = new FileStream("Log.txt", FileMode.Create);
Create a TextWriterTraceListener and register it as a listener, passing the FileStream to the constructor.
Create a trace switch using the name we declared earlier:
TraceSwitch generalSwitch = new TraceSwitch("MySwitch", "A descripion of this switch");
The trace switch controls how much information is written to the log and can be changed after the application is deployed by editing the App.Config file. Remember the example above had a value of zero? Here’s the complete list of available settings:
0 = Off
1 = Error (error messages)
2 = Warning (warning and error messages)
3 = Information (information, warning and error messages)
4 = Verbose (verbose, information, warning and error messages)
To begin writing to the log, use the Trace.WriteLineIf command which takes a boolean and a string. The string is only written to the log if the boolean is true. The TraceSwitch object has boolean properties that correspond to the different trace levels; TraceError, TraceWarning, TraceInfo and TraceVerbose.
The level of detail in the trace log can therefore be controlled by the value of the trace switch in the App.Config file, without changing the code. Pure magic.
Trace.WriteLineIf(generalSwitch.TraceError, "Error message written to trace log"); Trace.WriteLineIf(generalSwitch.TraceWarning, "Warning message written to trace log"); Trace.WriteLineIf(generalSwitch.TraceInfo, "Info message written to trace log"); Trace.WriteLineIf(generalSwitch.TraceVerbose, "Verbose message written to trace log");
For more information, MSDN is your friend: