Edit

Share via


How to: Create and Initialize Trace Sources

Note

This article is specific to .NET Framework. It doesn't apply to newer implementations of .NET, including .NET 6 and later versions.

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 (.NET Framework) 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.

    using System;
    using System.Diagnostics;
    
    class TraceTest
    {
    
        private static TraceSource mySource =
                new TraceSource("TraceSourceApp");
            static void Main(string[] args)
            {
               // Issue an error and a warning message. Only the error message
                // should be logged.
                Activity1();
    
                // Save the original settings from the configuration file.
                EventTypeFilter configFilter =
                    (EventTypeFilter)mySource.Listeners["console"].Filter;
    
                // Create a new event type filter that ensures
                // warning messages will be written.
                mySource.Listeners["console"].Filter =
                    new EventTypeFilter(SourceLevels.Warning);
    
                // Allow the trace source to send messages to listeners
                // for all event types. This statement will override
                // any settings in the configuration file.
                // If you do not change the switch level, the event filter
                // changes have no effect.
                mySource.Switch.Level = SourceLevels.All;
    
                // Issue a warning and a critical message. Both should be logged.
                Activity2();
    
                // 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.TraceEvent(TraceEventType.Warning, 2,
                    "Warning message.");
            }
            static void Activity3()
            {
                mySource.TraceEvent(TraceEventType.Error, 4,
                    "Error message.");
                mySource.TraceInformation("Informational message.");
            }
        }
    
    Imports System.Diagnostics
    
    Class TraceTest
    
        Private Shared mySource As New TraceSource("TraceSourceApp")
    
        Shared Sub Main(ByVal args() As String)
            ' Issue an error and a warning message. Only the error message
            ' should be logged.
            Activity1()
    
            ' Save the original settings from the configuration file.
            Dim configFilter As EventTypeFilter = CType(mySource.Listeners("console").Filter, EventTypeFilter)
    
            ' Create a new event type filter that ensures 
            ' warning messages will be written.
            mySource.Listeners("console").Filter = New EventTypeFilter(SourceLevels.Warning)
    
            ' Allow the trace source to send messages to listeners 
            ' for all event types. This statement will override 
            ' any settings in the configuration file.
            ' If you do not change the switch level, the event filter
            ' changes have no effect.
            mySource.Switch.Level = SourceLevels.All
    
            ' Issue a warning and a critical message. Both should be logged.
            Activity2()
    
            ' Restore the original filter settings.
            mySource.Listeners("console").Filter = configFilter
            Activity3()
            mySource.Close()
            Return
    
        End Sub
    
        Shared Sub Activity1()
            mySource.TraceEvent(TraceEventType.Error, 1, "Error message.")
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.")
    
        End Sub
    
        Shared Sub Activity2()
            mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.")
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.")
    
        End Sub
    
        Shared Sub Activity3()
            mySource.TraceEvent(TraceEventType.Error, 4, "Error message.")
            mySource.TraceInformation("Informational message.")
    
        End Sub
    End Class
    
  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.

    <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="Error"/>
              </add>
              <add name="myListener"/>
              <remove name="Default"/>
            </listeners>
          </source>
        </sources>
        <switches>
          <add name="sourceSwitch" value="Error"/>
        </switches>
        <sharedListeners>
          <add name="myListener"
            type="System.Diagnostics.TextWriterTraceListener"
            initializeData="myListener.log">
            <filter type="System.Diagnostics.EventTypeFilter"
              initializeData="Error"/>
          </add>
        </sharedListeners>
      </system.diagnostics>
    </configuration>
    

    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");
                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();
    
                // 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);
                Activity2();
    
                // 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.");
            }
        }
    }
    
    
    Imports System.Diagnostics
    Imports System.Threading
    
    
    
    Class Program
        Private Shared mySource As New TraceSource("TraceSourceApp")
    
        Shared Sub Main(ByVal args() As String)
            mySource.Switch = New SourceSwitch("sourceSwitch", "Error")
            mySource.Listeners.Remove("Default")
            Dim textListener As New TextWriterTraceListener("myListener.log")
            Dim console As 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()
    
            ' 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)
            Activity2()
    
            ' Change the filter settings for the console trace listener.
            mySource.Listeners("console").Filter = New EventTypeFilter(SourceLevels.Information)
            Activity3()
            mySource.Close()
            Return
    
        End Sub
    
        Shared Sub Activity1()
            mySource.TraceEvent(TraceEventType.Error, 1, "Error message.")
            mySource.TraceEvent(TraceEventType.Warning, 2, "Warning message.")
    
        End Sub
    
        Shared Sub Activity2()
            mySource.TraceEvent(TraceEventType.Critical, 3, "Critical message.")
            mySource.TraceInformation("Informational message.")
    
        End Sub
    
        Shared Sub Activity3()
            mySource.TraceEvent(TraceEventType.Error, 4, "Error message.")
            mySource.TraceInformation("Informational message.")
    
        End Sub
    End Class
    
    

See also