Wednesday, February 01, 2006

C# tracing and logging

Ok, no more excuses. Here's some of my tracing code. If you want to use an event log trace listener you can use this.

EventLogTraceListener myTraceListener = null;

public TracingDLL()
{
// Create a trace listener for the event log.
myTraceListener = new EventLogTraceListener("myEventLogSource");
// Add the event log trace listener to the collection.
Trace.Listeners.Add(myTraceListener);
// Write output to the event log.
Trace.WriteLine("Test output in TracingDLL");
Trace.Listeners.Remove("myEventLogSource");
}

In order to user a TraceSwitch you have to declare it in your code and then use it. You can either hard code the configuration, or you can use the config file as shown below.

TraceSwitch generalSwitch = new TraceSwitch("General", "Entire application");
Trace.WriteLineIf(generalSwitch.TraceError, "Write Error Line");
Trace.WriteLineIf(generalSwitch.TraceWarning, "Write Warning Line");
Trace.WriteLineIf(generalSwitch.TraceInfo, "Write Info");
Trace.WriteLineIf(generalSwitch.TraceVerbose, "Write Verbose.");












<-- The default Trace listener is Console />





No comments: