.NET Framework Class Library
TraceSwitch Class

Provides a multilevel switch to control tracing and debug output without recompiling your code.

Inheritance Hierarchy
SystemObject
   System.DiagnosticsSwitch
    System.DiagnosticsTraceSwitch

Namespace:   System.Diagnostics
Assembly:  System (in System.dll)
Syntax
Public Class TraceSwitch _
	Inherits [%$TOPIC/eb1fee91_en-us_VS_110_2_0_0_0_0%]
public class TraceSwitch : [%$TOPIC/eb1fee91_en-us_VS_110_2_0_1_0_0%]
public ref class TraceSwitch : public [%$TOPIC/eb1fee91_en-us_VS_110_2_0_2_0_0%]
type TraceSwitch =  
    class 
        inherit [%$TOPIC/eb1fee91_en-us_VS_110_2_0_3_0_0%] 
    end

The TraceSwitch type exposes the following members.

Constructors
  NameDescription
Public method TraceSwitch(String, String)Initializes a new instance of the TraceSwitch class, using the specified display name and description.
Public method TraceSwitch(String, String, String)Initializes a new instance of the TraceSwitch class, using the specified display name, description, and default value for the switch.
Top
Properties
  NameDescription
Public property AttributesGets the custom switch attributes defined in the application configuration file. (Inherited from Switch.)
Public property DescriptionGets a description of the switch. (Inherited from Switch.)
Public property DisplayNameGets a name used to identify the switch. (Inherited from Switch.)
Public property LevelGets or sets the trace level that determines the messages the switch allows.
Protected property SwitchSettingGets or sets the current setting for this switch. (Inherited from Switch.)
Public property TraceErrorGets a value indicating whether the switch allows error-handling messages.
Public property TraceInfoGets a value indicating whether the switch allows informational messages.
Public property TraceVerboseGets a value indicating whether the switch allows all messages.
Public property TraceWarningGets a value indicating whether the switch allows warning messages.
Protected property ValueGets or sets the value of the switch. (Inherited from Switch.)
Top
Methods
  NameDescription
Public method Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method GetHashCodeServes as the default hash function. (Inherited from Object.)
Protected method GetSupportedAttributesGets the custom attributes supported by the switch. (Inherited from Switch.)
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Protected method MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method OnSwitchSettingChangedUpdates and corrects the level for this switch. (Overrides SwitchOnSwitchSettingChanged.)
Protected method OnValueChangedSets the SwitchSetting property to the integer equivalent of the Value property. (Overrides SwitchOnValueChanged.)
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Top
Remarks

You can use a trace switch to filter out messages based on their importance. The TraceSwitch class provides the TraceError, TraceWarning, TraceInfo, and TraceVerbose properties to test the level of the switch. The Level property gets or sets the switch's TraceLevel.

You can set the level of a TraceSwitch through the application configuration file and then use the configured TraceSwitch level in your application. Alternately, you can create a TraceSwitch in your code and set the level directly to instrument a specific section of code.

To configure a TraceSwitch, edit the configuration file for your application. In this file, you can add or remove a switch, set a switch's value, or clear all the switches previously set by the application. The configuration file should be formatted like the following example:

<configuration>
  <system.diagnostics>
    <switches>
      <add name="mySwitch" value="1" />
    </switches>
  </system.diagnostics>
</configuration>

This configuration section defines a TraceSwitch with the DisplayName set to mySwitch, and the Level set to 1, which corresponds to the enumeration value TraceLevelError.

NoteNote

In the .NET Framework version 2.0, you can use text to specify the value for a switch. For example, true for a BooleanSwitch or the text representing an enumeration value, such as Error for a TraceSwitch. The line <add name="mySwitch" value="Error" /> is equivalent to <add name="mySwitch" value="1" />.

In your application, you can use the configured switch level by creating a TraceSwitch with the same name, as shown in the following example:

Private Shared appSwitch As new TraceSwitch("mySwitch", _
    "Switch in config file")

Public Shared Sub Main(args As String())
    '...
    Console.WriteLine("Trace switch {0} configured as {1}",
    appSwitch.DisplayName, appSwitch.Level.ToString())
    If appSwitch.TraceError = True   Then 
        '... 
    End If 
End Sub
private static TraceSwitch appSwitch = new TraceSwitch("mySwitch",
    "Switch in config file");

public static void Main(string[] args)
{
    //...
    Console.WriteLine("Trace switch {0} configured as {1}",
    appSwitch.DisplayName, appSwitch.Level.ToString());
    if (appSwitch.TraceError)
    {
        //...
    }
}
private:
    static TraceSwitch^ appSwitch = gcnew TraceSwitch("mySwitch",
        "Switch in config file");

public:
    static void Main(array<String^>^ args)
    {
        //...
        Console::WriteLine("Trace switch {0} configured as {1}",
        appSwitch->DisplayName, appSwitch->Level.ToString());
        if (appSwitch->TraceError)
        {
            //...
        }
    }

By default, the switch Level property is set using the value specified in the configuration file. If the TraceSwitch constructor cannot find initial switch settings in the configuration file, the Level of the new switch defaults to TraceLevelOff.

You must enable tracing or debugging to use a switch. The following syntax is compiler specific. If you use compilers other than C# or Visual Basic, refer to the documentation for your compiler.

  • To enable debugging in C#, add the /d:DEBUG flag to the compiler command line when you compile your code, or add #define DEBUG to the top of your file. In Visual Basic, add the /d:DEBUG=True flag to the compiler command line.

  • To enable tracing in C#, add the /d:TRACE flag to the compiler command line when you compile your code, or add #define TRACE to the top of your file. In Visual Basic, add the /d:TRACE=True flag to the compiler command line.

NoteNote

These debug and trace compiler switches are not required when using the TraceSwitch class in isolation. They are only required in conjunction with Trace or Debug methods that are conditionally compiled.

For more information on instrumenting your application, see Debug and Trace. For more information about configuring and using trace switches, see Trace Switches.

NoteNote

To improve performance, you can make TraceSwitch members static in your class.

Examples

The following code example creates a new TraceSwitch and uses the switch to determine whether to print error messages. The switch is created at the class level. MyMethod writes the first error message if the Level property is set to TraceLevelError or higher. However, MyMethod does not write the second error message if the Level is less than TraceLevelVerbose.

    ' Class-level declaration. 
    ' Create a TraceSwitch to use in the entire application.  
    Private Shared mySwitch As New TraceSwitch("General", "Entire Application")    

    Public Shared Sub MyMethod()
        ' Write the message if the TraceSwitch level is set to Error or higher. 
        If mySwitch.TraceError Then
            Console.WriteLine("My error message.")
        End If  
        ' Write the message if the TraceSwitch level is set to Verbose. 
        If mySwitch.TraceVerbose Then
            Console.WriteLine("My second error message.")
        End If 
    End Sub 

    Public Shared Sub Main()
        ' Run the method that prints error messages based on the switch level.
        MyMethod()
    End Sub
//Class-level declaration. 
 /* Create a TraceSwitch to use in the entire application.*/ 
 static TraceSwitch mySwitch = new TraceSwitch("General", "Entire Application");

 static public void MyMethod() {
    // Write the message if the TraceSwitch level is set to Error or higher. 
    if(mySwitch.TraceError)
       Console.WriteLine("My error message.");

    // Write the message if the TraceSwitch level is set to Verbose. 
    if(mySwitch.TraceVerbose)
       Console.WriteLine("My second error message.");
 }

 public static void Main(string[] args) {
    // Run the method that prints error messages based on the switch level.
    MyMethod();
 }
 
// Class-level declaration. 
   /* Create a TraceSwitch to use in the entire application.*/ 
private:
   static TraceSwitch^ mySwitch = gcnew TraceSwitch( "General", "Entire Application" );

public:
   static void MyMethod()
   {
      // Write the message if the TraceSwitch level is set to Error or higher. 
      if ( mySwitch->TraceError )
         Console::WriteLine( "My error message." );

      // Write the message if the TraceSwitch level is set to Verbose. 
      if ( mySwitch->TraceVerbose )
         Console::WriteLine( "My second error message." );
   }

   static void main()
   {
      // Run the method that prints error messages based on the switch level.
      MyMethod();
   }
Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.