Dec 18, 2008

TraceSource

In my post How to control whether to output Trace, I discussed how to output behavior of Trace object. We can control destination with the system.diagnostics.trace section, and control the when to output Trace by using listener's filter or using switch.

But .net offer a better object to replace Trace object, that is TraceSource. It explicitly explicitly works with listener and switch to give user a better control. Here is an article on this issue. Below is some demo code. For new application, we should only use TraceSource object instead of Trace. Please note that now you can use both Listner filter and switch to control whether to output. The reason to use TraceSource over Trace is that TraceSource is instance object, Trace is a static object. You may use different TraceSource to trace different component. This is especially useful to third party component so that their trace may be independent of user's trace. Here is another artical Extending System.Diagnostics

class Program
{
    public static TraceSource MasterTraceSource = new TraceSource("TraceSourceApp");

    static void Main(string[] args)
    {
        Trace.WriteLine("program started...");
        Trace.Assert(1 != 1, "something wrong");
        // 
        MasterTraceSource.TraceInformation("Trace information");
        MasterTraceSource.TraceEvent(TraceEventType.Error, 1, "Error message.");
        MasterTraceSource.TraceEvent(TraceEventType.Verbose, 2, "Warning message.");
        MasterTraceSource.Close();
        return;
    }

}