How To: Create and Initialize Trace SourcesĀ 

Trace sources can be created and initialized with or without the use of configuration files. The recommended approach is to use configuration files to facilitate the reconfiguration of the traces produced by trace sources at run time.

To create and initialize a trace source using a configuration file

  1. The following sample code is intended to execute in conjunction with an application configuration file (shown in step 2). The configuration file initializes the settings for the trace source at the time the application is initialized. The application can dynamically change the properties set by the configuration file to override any settings specified by the user. For example, you might want to assure that critical messages are always sent to a text file, regardless of the current configuration settings. The following sample code demonstrates the overriding of configuration file settings to assure critical messages are output to the trace listeners. Changing the configuration file settings while the application is executing does not change the initial settings. To do that you must either restart the application or programmatically refresh the application using the Refresh method.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    namespace TraceSourceApp
    {
        class Program
        {
            private static TraceSource mySource = 
                new TraceSource("TraceSourceApp");
            static void Main(string[] args)
            {
                Activity1();
    
                // Change the event type for which tracing occurs.
                // The console trace listener must be specified 
                // in the configuration file. First, save the original
                // settings from the configuration file.
                EventTypeFilter configFilter = 
                    (EventTypeFilter)mySource.Listeners["console"].Filter;
    
                // Then create a new event type filter that ensures 
                // critical messages will be written.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Critical);
                Activity2();
    
                // Allow the trace source to send messages to listeners 
                // for all event types. This statement will override 
                // any settings in the configuration file.
                mySource.Switch.Level = SourceLevels.All;
    
                // Restore the original filter settings.
                mySource.Listeners["console"].Filter = configFilter;
                Activity3();
                mySource.Close();
                return;
            }
            static void Activity1()
            {
                mySource.TraceEvent(TraceEventType.Error, 1, 
                    "Error message.");
                mySource.TraceEvent(TraceEventType.Warning, 2, 
                    "Warning message.");
            }
            static void Activity2()
            {
                mySource.TraceEvent(TraceEventType.Critical, 3, 
                    "Critical message.");
                mySource.TraceInformation("Informational message.");
            }
            static void Activity3()
            {
                mySource.TraceEvent(TraceEventType.Error, 4, 
                    "Error message.");
                mySource.TraceInformation("Informational message.");
            }
        }
    }
    
  2. Create the following configuration file to initialize the TraceSource TraceSourceApp in the code example. The configuration file for an application hosted by the executable host is in the same directory as the application. The name of the configuration file is the name of the application with a .config extension. For our example, TraceSourceApp.exe can be associated with a configuration file called TraceSourceApp.exe.config. The following configuration file example shows how to initialize a console trace listener and a text writer trace listener for the trace source that is created in the preceding step. In addition to configuring the trace listeners, the configuration file creates filters for both of the listeners and creates a source switch for the trace source. Two techniques are shown for adding trace listeners: adding the listener directly to the trace source and adding a listener to the shared listeners collection and then adding it by name to the trace source. The filters identified for the two listeners are initialized with different source levels. This results in some messages being written by only one of the two listeners.

    <configuration>
      <system.diagnostics>
        <sources>
          <source name="TraceSourceApp" 
            switchName="sourceSwitch" 
            switchType="System.Diagnostics.SourceSwitch">
            <listeners>
              <add name="console" 
                type="System.Diagnostics.ConsoleTraceListener">
                <filter type="System.Diagnostics.EventTypeFilter" 
                  initializeData="Warning"/>
              </add>
              <add name="myListener"/>
              <remove name="Default"/>
            </listeners>
          </source>
        </sources>
        <switches>
          <add name="sourceSwitch" value="Warning"/>
        </switches>
        <sharedListeners>
          <add name="myListener" 
            type="System.Diagnostics.TextWriterTraceListener" 
            initializeData="myListener.log">
            <filter type="System.Diagnostics.EventTypeFilter" 
              initializeData="Error"/>
          </add>
        </sharedListeners>
      </system.diagnostics>
    </configuration>
    

To initialize trace sources, listeners, and filters without a configuration file

  • You can instrument tracing through a trace source entirely though code without the use of a configuration file. This is not recommended practice, but there may be circumstances in which you do not want to depend on configuration files to ensure tracing.

    using System;
    using System.Diagnostics;
    using System.Threading;
    
    namespace TraceSourceApp
    {
        class Program
        {
            private static TraceSource mySource =
                new TraceSource("TraceSourceApp");
            static void Main(string[] args)
            {
                mySource.Switch = new SourceSwitch("sourceSwitch", "Error");
                mySource.Listeners.Remove("Default");
                TextWriterTraceListener textListener =
                    new TextWriterTraceListener("myListener.log");
                ConsoleTraceListener console =
                    new ConsoleTraceListener(false);
                console.Filter =
                    new EventTypeFilter(SourceLevels.Information);
                console.Name = "console";
                textListener.Filter =
                    new EventTypeFilter(SourceLevels.Error);
                mySource.Listeners.Add(console);
                mySource.Listeners.Add(textListener);
                Activity1();
    
                // Set the filter settings for the 
                // console trace listener.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Critical);
                Activity2();
    
                // Allow the trace source to send messages to 
                // listeners for all event types. 
                mySource.Switch.Level = SourceLevels.All;
    
                // Change the filter settings for the console trace listener.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Information);
                Activity3();
                mySource.Close();
                return;
            }
            static void Activity1()
            {
                mySource.TraceEvent(TraceEventType.Error, 1,
                    "Error message.");
                mySource.TraceEvent(TraceEventType.Warning, 2,
                    "Warning message.");
            }
            static void Activity2()
            {
                mySource.TraceEvent(TraceEventType.Critical, 3,
                    "Critical message.");
                mySource.TraceInformation("Informational message.");
            }
            static void Activity3()
            {
                mySource.TraceEvent(TraceEventType.Error, 4,
                    "Error message.");
                mySource.TraceInformation("Informational message.");
            }
        }
    }
    

See Also

Reference

TraceSource
TextWriterTraceListener
ConsoleTraceListener
EventTypeFilter

Other Resources

Tracing and Instrumenting Applications