How to: Create and Initialize Trace Sources

How to: Create and Initialize Trace Sources


The TraceSource class is used by applications to produce traces that can be associated with the application. TraceSource provides tracing methods that allow you to easily trace events, trace data, and issue informational traces. Trace output from TraceSource can be created and initialized with or without the use of configuration files. This topic provides instructions for both options. However, we recommend that you 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. Create a Visual Studio console application project and replace the supplied code with the following code. This code logs errors and warnings and outputs some of them to the console, and some of them to the myListener file that is created by the entries in the configuration file.

    // Call the Constructor of ContractReference.
    ContractReference myContractReference = new ContractReference();
  2. Add an application configuration file, if one is not present, to the project to initialize the trace source named TraceSourceApp in the code example in step 1.

  3. Replace the default configuration file content with the following settings to initialize a console trace listener and a text writer trace listener for the trace source that was created in step 1.

          <source name="TraceSourceApp" 
              <add name="console" 
                <filter type="System.Diagnostics.EventTypeFilter" 
              <add name="myListener"/>
              <remove name="Default"/>
          <add name="sourceSwitch" value="Error"/>
          <add name="myListener" 
            <filter type="System.Diagnostics.EventTypeFilter" 

    In addition to configuring the trace listeners, the configuration file creates filters for both 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.

    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 ensure that critical messages are always sent to a text file, regardless of the current configuration settings. The example code demonstrates how to override configuration file settings to ensure that 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 change the settings, you must either restart the application or programmatically refresh the application by using the Trace.Refresh method.

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

  • Use the following example code to enable tracing through a trace source without using a configuration file. This is not a 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");
                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);
                // Allow the trace source to send messages to 
                // listeners for all event types. Currently only 
                // error messages or higher go to the listeners.
                // Messages must get past the source switch to 
                // get to the listeners, regardless of the settings 
                // for the listeners.
                mySource.Switch.Level = SourceLevels.All;
                // Set the filter settings for the 
                // console trace listener.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Critical);
                // Change the filter settings for the console trace listener.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Information);
            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.");
© 2015 Microsoft