Sep 20, 2007

Best practice of using Trace and Debug

class Program
            {

            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;
            }



            private static TraceSource mySource = new TraceSource("TraceSourceApp");
            public static TraceSource MasterTraceSource
            {
            get
            {
            return mySource;
            }
            }
            }

            

            <?xml version="1.0" encoding="utf-8" ?>
            <configuration>
            <system.diagnostics>
            <sources>
            <!--
            "TraceSourceApp" is the name of TraceSource, new TraceSource("TraceSourceApp")
            switch name reference the name in source switch, it controls whether send
            the information to listners
            -->
            <source name="TraceSourceApp" switchName="sourceSwitch" switchType="System.Diagnostics.SourceSwitch">
            <listeners>
            <add name="consoleListner" />
            <add name="textfileListner"/>
            <remove name="Default"/>
            </listeners>
            </source>
            </sources>

            <trace autoflush="true" indentsize="4">
            <listeners>
            <add name="consoleListner" />
            <remove name="Default" />
            </listeners>
            </trace>

            <switches>
            <add name="sourceSwitch" value="Verbose"/>
            </switches>

            <sharedlisteners>
            <add name="consoleListner" type="System.Diagnostics.ConsoleTraceListener">
            <!--filter is optional, it controls whether to output info to underlining datasource-->
            <filter type="System.Diagnostics.EventTypeFilter" initializeData="Error"/>
            </add>
            <add name="textfileListner" type="System.Diagnostics.TextWriterTraceListener" initializeData="textfileListner.log">
            <filter type="System.Diagnostics.EventTypeFilter" initializeData="Verbose"/>
            </add>
            </sharedListeners>



            </system.diagnostics>
            </configuration>

When you enable system.web.trace enabled ="true" requestLimit="20" writeToDiagnosticsTrace ="true " pageOutput ="false", the trace not only ouput to page or trace.axd, it will be also ouput system.diagnostic.trace listner. But it is much simpler.