1 out of 5 rated this helpful - Rate this topic

TraceSource Class

Updated: August 2010

Provides a set of methods and properties that enable applications to trace the execution of code and associate trace messages with their source.

System.Object
  System.Diagnostics.TraceSource

Namespace:  System.Diagnostics
Assembly:  System (in System.dll)
public class TraceSource

The TraceSource type exposes the following members.

  Name Description
Public method TraceSource(String) Initializes a new instance of the TraceSource class, using the specified name for the source.
Public method TraceSource(String, SourceLevels) Initializes a new instance of the TraceSource class, using the specified name for the source and the default source level at which tracing is to occur.
Top
  Name Description
Public property Attributes Gets the custom switch attributes defined in the application configuration file.
Public property Listeners Gets the collection of trace listeners for the trace source.
Public property Name Gets the name of the trace source.
Public property Switch Gets or sets the source switch value.
Top
  Name Description
Public method Close Closes all the trace listeners in the trace listener collection.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Flush Flushes all the trace listeners in the trace listener collection.
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Protected method GetSupportedAttributes Gets the custom attributes supported by the trace source.
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Public method TraceData(TraceEventType, Int32, Object) Writes trace data to the trace listeners in the Listeners collection using the specified event type, event identifier, and trace data.
Public method TraceData(TraceEventType, Int32, Object[]) Writes trace data to the trace listeners in the Listeners collection using the specified event type, event identifier, and trace data array.
Public method TraceEvent(TraceEventType, Int32) Writes a trace event message to the trace listeners in the Listeners collection using the specified event type and event identifier.
Public method TraceEvent(TraceEventType, Int32, String) Writes a trace event message to the trace listeners in the Listeners collection using the specified event type, event identifier, and message.
Public method TraceEvent(TraceEventType, Int32, String, Object[]) Writes a trace event to the trace listeners in the Listeners collection using the specified event type, event identifier, and argument array and format.
Public method TraceInformation(String) Writes an informational message to the trace listeners in the Listeners collection using the specified message.
Public method TraceInformation(String, Object[]) Writes an informational message to the trace listeners in the Listeners collection using the specified object array and formatting information.
Public method TraceTransfer Writes a trace transfer message to the trace listeners in the Listeners collection using the specified numeric identifier, message, and related activity identifier.
Top

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 controlled by configuration file settings. The configuration file is located in the folder with the application executable and has the name of the application with the .config file name extension added. For example, the name of the configuration file for TraceSourceSample.exe is TraceSourceSample.exe.config. The configuration file can be used to determine where the trace information is to be sent and what levels of activity are to be traced. The following example shows the contents of a sample application configuration file.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="TraceTest" switchName="SourceSwitch" 
        switchType="System.Diagnostics.SourceSwitch" >
        <listeners>
          <add name="console" />
          <remove name ="Default" />
        </listeners>
      </source>
    </sources>
    <switches>
      <!-- You can set the level at which tracing is to occur -->
      <add name="SourceSwitch" value="Warning" />
        <!-- You can turn tracing off -->
        <!--add name="SourceSwitch" value="Off" -->
    </switches>
    <sharedListeners>
      <add name="console" 
        type="System.Diagnostics.ConsoleTraceListener" 
        initializeData="false"/>
    </sharedListeners>
    <trace autoflush="true" indentsize="4">
      <listeners>
        <add name="console" />
      </listeners>
    </trace>
  </system.diagnostics>
</configuration>

The TraceSource class is identified by the name of a source, typically the name of the application. The trace messages coming from a particular component can be initiated by a particular trace source, allowing all messages coming from that component to be easily identified.

TraceSource defines tracing methods but does not actually provide any specific mechanism for generating and storing tracing data. The tracing data is produced by trace listeners, which are plug-ins that can be loaded by trace sources.

NoteNote

You should not call the tracing methods during finalization. Doing so can result in an ObjectDisposedException being thrown.

You can customize the tracing output's target by adding or removing TraceListener instances to or from the collection stored in the TraceSource.Listeners property. By default, trace output is produced using an instance of the DefaultTraceListener class. The preceding configuration file example demonstrates removing the DefaultTraceListener and adding a ConsoleTraceListener to produce the trace output for the trace source. For more information, see <listeners> Element for <source> and <sharedListeners> Element.

NoteNote

Adding a trace listener to the Listeners collection can cause an exception to be thrown while tracing, if a resource used by the trace listener is not available. The conditions and the exception thrown depend on the trace listener and cannot be enumerated in this topic. It may be useful to place calls to the TraceSource methods in try/catch blocks to detect and handle any exceptions from trace listeners.

The SourceSwitch class provides the means to dynamically control the tracing output. The preceding configuration file example shows how you can turn off tracing from a trace source and control the level at which tracing occurs. You can modify the value of the source switch without recompiling your application. For information on using the configuration file to set a switch, see Switch and How to: Configure Trace Switches.

NoteNote

If you modify a configuration file while an application is executing, the application must be stopped and restarted or the Refresh method must be called before the new settings take effect.

The TraceEventType enumeration is used to define the event type of the trace message. Trace filters use the TraceEventType to determine if a trace listener should produce the trace message.

The trace listeners can optionally have an additional layer of filtering through a trace filter. If a trace listener has an associated filter, the listener calls the ShouldTrace method on that filter to determine whether or not to produce the trace information.

The trace listeners use the values of the Trace class properties Indent, IndentSize, and AutoFlush to format trace output. You can use configuration file attributes to set the Indent, IndentSize, and AutoFlush properties. The following example sets the AutoFlush property to false and the IndentSize property to 3.

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="3" />
  </system.diagnostics>
</configuration>

The following code example shows the use of the TraceSource class to forward traces to listeners. The example also demonstrates switch and filter usage.


// The following configuration file can be used with this sample.
// When using a configuration file #define ConfigFile.
//<configuration>
//    <system.diagnostics>
//        <sources>
//            <source name="TraceTest" switchName="SourceSwitch" switchType="System.Diagnostics.SourceSwitch" >
//                <listeners>
//                    <add name="console" type="System.Diagnostics.ConsoleTraceListener" initializeData="false" />
//                    <remove name ="Default" />
//                </listeners>
//            </source>
//        </sources>
//        <switches>
//            <!-- You can set the level at which tracing is to occur -->
//            <add name="SourceSwitch" value="Warning" />
//            <!-- You can turn tracing off -->
//            <!--add name="SourceSwitch" value="Off" -->
//        </switches>
//        <trace autoflush="true" indentsize="4"></trace>
//    </system.diagnostics>
//</configuration>
#define TRACE
//#define ConfigFile

using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.IO;
using System.Security.Permissions;

namespace Testing
{
    class TraceTest
    {
        // Initialize the trace source.
        static TraceSource ts = new TraceSource("TraceTest");
        [SwitchAttribute("SourceSwitch", typeof(SourceSwitch))]
        static void Main()
        {
            try
            {
                // Initialize trace switches.
#if(!ConfigFile)
                SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
                ts.Switch = sourceSwitch;
                int idxConsole = ts.Listeners.Add(new System.Diagnostics.ConsoleTraceListener());
                ts.Listeners[idxConsole].Name = "console";
#endif
                DisplayProperties(ts);
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.Callstack;
                ts.TraceEvent(TraceEventType.Warning, 1);
                ts.Listeners["console"].TraceOutputOptions = TraceOptions.DateTime;
                // Issue file not found message as a warning.
                ts.TraceEvent(TraceEventType.Warning, 2, "File Test not found");
                // Issue file not found message as a verbose event using a formatted string.
                ts.TraceEvent(TraceEventType.Verbose, 3, "File {0} not found.", "test");
                // Issue file not found message as information.
                ts.TraceInformation("File {0} not found.", "test");
                ts.Listeners["console"].TraceOutputOptions |= TraceOptions.LogicalOperationStack;
                // Issue file not found message as an error event.
                ts.TraceEvent(TraceEventType.Error, 4, "File {0} not found.", "test");
                // Test the filter on the ConsoleTraceListener.
                ts.Listeners["console"].Filter = new SourceFilter("No match");
                ts.TraceData(TraceEventType.Error, 5,
                    "SourceFilter should reject this message for the console trace listener.");
                ts.Listeners["console"].Filter = new SourceFilter("TraceTest");
                ts.TraceData(TraceEventType.Error, 6,
                    "SourceFilter should let this message through on the console trace listener.");
                ts.Listeners["console"].Filter = null;
                // Use the TraceData method. 
                ts.TraceData(TraceEventType.Warning, 7, new object());
                ts.TraceData(TraceEventType.Warning, 8, new object[] { "Message 1", "Message 2" });
                // Activity tests.
                ts.TraceEvent(TraceEventType.Start, 9, "Will not appear until the switch is changed.");
                ts.Switch.Level = SourceLevels.ActivityTracing | SourceLevels.Critical;
                ts.TraceEvent(TraceEventType.Suspend, 10, "Switch includes ActivityTracing, this should appear");
                ts.TraceEvent(TraceEventType.Critical, 11, "Switch includes Critical, this should appear");
                ts.Flush();
                ts.Close();
                Console.WriteLine("Press any key to exit.");
                Console.Read();
            }
            catch (Exception e)
            {
                // Catch any unexpected exception.
                Console.WriteLine("Unexpected exception: " + e.ToString());
                Console.Read();
            }
        }
        public static void DisplayProperties(TraceSource ts)
        {
            Console.WriteLine("TraceSource name = " + ts.Name);
            Console.WriteLine("TraceSource switch level = " + ts.Switch.Level);
            Console.WriteLine("TraceSource switch = " + ts.Switch.DisplayName);
            SwitchAttribute[] switches = SwitchAttribute.GetAll(Assembly.GetExecutingAssembly());
            for (int i = 0; i < switches.Length; i++)
            {
                Console.WriteLine("Switch name = " + switches[i].SwitchName);
                Console.WriteLine("Switch type = " + switches[i].SwitchType);
            }
#if(ConfigFile)
            // Get the custom attributes for the TraceSource.
            Console.WriteLine("Number of custom trace source attributes = "
                + ts.Attributes.Count);
            foreach (DictionaryEntry de in ts.Attributes)
                Console.WriteLine("Custom trace source attribute = "
                    + de.Key + "  " + de.Value);
            // Get the custom attributes for the trace source switch.
            foreach (DictionaryEntry de in ts.Switch.Attributes)
                Console.WriteLine("Custom switch attribute = "
                    + de.Key + "  " + de.Value);
#endif
            Console.WriteLine("Number of listeners = " + ts.Listeners.Count);
            foreach (TraceListener traceListener in ts.Listeners)
            {
                Console.Write("TraceListener: " + traceListener.Name + "\t");
                // The following output can be used to update the configuration file.
                Console.WriteLine("AssemblyQualifiedName = " +
                    (traceListener.GetType().AssemblyQualifiedName));
            }
        }
    }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.

Date

History

Reason

August 2010

Corrected type safety information.

Content bug fix.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
delayed validation gotcha!

Given the slightly invalid configuration:

<source name="foo" switchValue="off">
<listeners>
<clear/>
<add name="debug_log"/>
</listeners>
</source>

Application will load fine, however the code:

ts = new TraceSource("foo", SourceLevels.Warning);
ts.TraceEvent(TraceEventType.Verbose, 0, "message");

Raises the following:

System.ArgumentException: Requested value 'off' was not found.
at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase)
at System.Diagnostics.TraceSource.Initialize()
at System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String message)


This is because the switchValue configuration isn't tested until something gets traced.

Info ID
Why isn't Information Id incremented after TraceInformation("Some Info") calls $0$0 $0 $0System.Diagnostics.Test Information: 0 : Some info$0 $0$0 $0 $0after second call$0 $0$0 $0 $0System.Diagnostics.Test Information: 0 : Some info$0 $0$0 $0 $0Is there any possibility to increment Info's Id?$0 $0$0 $0 $0Thanks.$0 $0$0 $0