.NET Framework Class Library
ConsoleTraceListener Class

Directs tracing or debugging output to either the standard output or the standard error stream.

Namespace:   System.Diagnostics
Assembly:  System (in System.dll)
Syntax
<[%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_0_0_0%]([%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_0_0_1%].LinkDemand, Synchronization := True)> _
Public Class ConsoleTraceListener _
	Inherits [%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_0_0_2%]
[[%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_1_0_0%]([%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_1_0_1%].LinkDemand, Synchronization = true)]
public class ConsoleTraceListener : [%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_1_0_2%]
[[%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_2_0_0%]([%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_2_0_1%]::LinkDemand, Synchronization = true)]
public ref class ConsoleTraceListener : public [%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_2_0_2%]
[<[%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_3_0_0%]([%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_3_0_1%].LinkDemand, Synchronization = true)>]
type ConsoleTraceListener =  
    class 
        inherit [%$TOPIC/f5tkwdf2_en-us_VS_110_2_0_3_0_2%] 
    end

The ConsoleTraceListener type exposes the following members.

Constructors
  NameDescription
Public method ConsoleTraceListenerInitializes a new instance of the ConsoleTraceListener class with trace output written to the standard output stream.
Public method ConsoleTraceListener(Boolean)Initializes a new instance of the ConsoleTraceListener class with an option to write trace output to the standard output stream or the standard error stream.
Top
Properties
  NameDescription
Public property AttributesGets the custom trace listener attributes defined in the application configuration file. (Inherited from TraceListener.)
Public property FilterGets and sets the trace filter for the trace listener. (Inherited from TraceListener.)
Public property IndentLevelGets or sets the indent level. (Inherited from TraceListener.)
Public property IndentSizeGets or sets the number of spaces in an indent. (Inherited from TraceListener.)
Public property IsThreadSafeGets a value indicating whether the trace listener is thread safe. (Inherited from TraceListener.)
Public property NameGets or sets a name for this TraceListener. (Inherited from TraceListener.)
Protected property NeedIndentGets or sets a value indicating whether to indent the output. (Inherited from TraceListener.)
Public property TraceOutputOptionsGets or sets the trace output options. (Inherited from TraceListener.)
Public property WriterGets or sets the text writer that receives the tracing or debugging output. (Inherited from TextWriterTraceListener.)
Top
Methods
  NameDescription
Public method CloseCloses the output to the stream specified for this trace listener. (Overrides TextWriterTraceListenerClose.)
Public method CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method DisposeReleases all resources used by the TraceListener. (Inherited from TraceListener.)
Protected method Dispose(Boolean)Infrastructure. Disposes this TextWriterTraceListener object. (Inherited from TextWriterTraceListener.)
Public method Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public method Fail(String)Emits an error message to the listener you create when you implement the TraceListener class. (Inherited from TraceListener.)
Public method Fail(String, String)Emits an error message and a detailed error message to the listener you create when you implement the TraceListener class. (Inherited from TraceListener.)
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 FlushFlushes the output buffer for the Writer. (Inherited from TextWriterTraceListener.)
Public method GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method GetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetSupportedAttributesGets the custom attributes supported by the trace listener. (Inherited from TraceListener.)
Public method GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method ToStringReturns a string that represents the current object. (Inherited from Object.)
Public method TraceData(TraceEventCache, String, TraceEventType, Int32, Object)Writes trace information, a data object and event information to the listener specific output. (Inherited from TraceListener.)
Public method TraceData(TraceEventCache, String, TraceEventType, Int32, Object)Writes trace information, an array of data objects and event information to the listener specific output. (Inherited from TraceListener.)
Public method TraceEvent(TraceEventCache, String, TraceEventType, Int32)Writes trace and event information to the listener specific output. (Inherited from TraceListener.)
Public method TraceEvent(TraceEventCache, String, TraceEventType, Int32, String)Writes trace information, a message, and event information to the listener specific output. (Inherited from TraceListener.)
Public method TraceEvent(TraceEventCache, String, TraceEventType, Int32, String, Object)Writes trace information, a formatted array of objects and event information to the listener specific output. (Inherited from TraceListener.)
Public method TraceTransferWrites trace information, a message, a related activity identity and event information to the listener specific output. (Inherited from TraceListener.)
Public method Write(Object)Writes the value of the object's ToString method to the listener you create when you implement the TraceListener class. (Inherited from TraceListener.)
Public method Write(String)Writes a message to this instance's Writer. (Inherited from TextWriterTraceListener.)
Public method Write(Object, String)Writes a category name and the value of the object's ToString method to the listener you create when you implement the TraceListener class. (Inherited from TraceListener.)
Public method Write(String, String)Writes a category name and a message to the listener you create when you implement the TraceListener class. (Inherited from TraceListener.)
Protected method WriteIndentWrites the indent to the listener you create when you implement this class, and resets the NeedIndent property to false. (Inherited from TraceListener.)
Public method WriteLine(Object)Writes the value of the object's ToString method to the listener you create when you implement the TraceListener class, followed by a line terminator. (Inherited from TraceListener.)
Public method WriteLine(String)Writes a message to this instance's Writer followed by a line terminator. The default line terminator is a carriage return followed by a line feed (\r\n). (Inherited from TextWriterTraceListener.)
Public method WriteLine(Object, String)Writes a category name and the value of the object's ToString method to the listener you create when you implement the TraceListener class, followed by a line terminator. (Inherited from TraceListener.)
Public method WriteLine(String, String)Writes a category name and a message to the listener you create when you implement the TraceListener class, followed by a line terminator. (Inherited from TraceListener.)
Top
Remarks

Use the ConsoleTraceListener class to write trace and debugging messages to the console. You can initialize a ConsoleTraceListener object to write trace messages to the ConsoleOut stream or to the ConsoleError stream.

Important noteImportant

IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in atry/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the IDisposable interface topic.

When trace and debugging output is enabled, the ConsoleTraceListener messages are written to the specified SystemConsole stream, which is similar to the way messages are written with the ConsoleWrite or ConsoleWriteLine methods. In a console application, the SystemConsole output and error streams write messages to the existing console window, or you can redirect the streams to write to a System.IOTextWriter instance.

NoteNote

If the console does not exist, as in a Windows-based application, messages written to the console are not displayed.

Add a ConsoleTraceListener object to the appropriate Listeners collection if you want messages written through Trace, TraceSource, or Debug to be written to the console. In addition, you can write messages directly to the console using the TraceWrite or TraceWriteLine methods.

NoteNote

The Debug and Trace classes share the same TraceListenerCollection collection, accessed through their respective Listeners properties. If you add a ConsoleTraceListener object to the collection using one of these classes, the other class automatically uses the same listener.

Most compilers enable trace and debug output through conditional compilation flags. If you do not enable tracing or debugging, the messages written through the System.DiagnosticsDebug and System.DiagnosticsTrace classes are effectively ignored. The syntax to enable trace and debug output 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 you can 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.

You can add a ConsoleTraceListener object to the Listeners collection in your code, or you can add a ConsoleTraceListener object to the Listeners collection through the application configuration file. Add the ConsoleTraceListener object in your code to write messages for a specific code section or execution path. Add the ConsoleTraceListener object in your application configuration file to direct all trace and debug messages to the console while the application executes.

To write trace and debug messages to the console for a specific section of code, initialize a ConsoleTraceListener object and add it to the Listeners collection. Instrument the section of code that contains messages using the Trace or Debug classes. At the end of the code section, remove the ConsoleTraceListener object from the Listeners collection, and call the Close method on the ConsoleTraceListener.

To direct all trace and debug messages to the console while the application executes, add a ConsoleTraceListener object to the application configuration file. Edit the configuration file that corresponds to the name of your application, or the app.config file in a Visual Studio 2005 project. In this file, insert an element for a ConsoleTraceListener.

The following example adds a ConsoleTraceListener object named configConsoleListener to the Listeners collection.

<configuration>
  <system.diagnostics>
    <trace autoflush="false" indentsize="4">
      <listeners>
        <add name="configConsoleListener"  
          type="System.Diagnostics.ConsoleTraceListener" />
      </listeners>
    </trace>
  </system.diagnostics>
 </configuration>

For details about adding trace listeners in the application configuration file, see <listeners> Element for <trace>.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

Examples

The following code example implements a console application consisting of a class with two public methods.

The Main method examines the command-line arguments and determines if trace output should be directed to the standard error stream or the standard output stream. Main creates and initializes a ConsoleTraceListener object for the specified Console output stream, and adds this object to the trace listener collection. It then calls the WriteEnvironmentInfoToTrace method, which writes details about the executing environment and the trace listener configuration to the trace output.

When the example application runs, the environment and trace configuration details are written to the specified console output stream through the ConsoleTraceListener object.

' Define the TRACE constant, which enables trace output to the  
' Trace.Listeners collection. Typically, this constant is defined 
' as a compilation argument.
#Const TRACE = True 

Imports System
Imports System.Diagnostics

Public Class ConsoleTraceSample

    ' Define a simple method to write details about the current executing  
    ' environment to the trace listener collection. 
    Public Shared Sub WriteEnvironmentInfoToTrace()

        Dim methodName As String = "WriteEnvironmentInfoToTrace"

        Trace.Indent()
        Trace.WriteLine(DateTime.Now.ToString() & " - Start of " & methodName)
        Trace.Indent()

        ' Write details on the executing environment to the trace output.
        Trace.WriteLine("Operating system: " & _
            System.Environment.OSVersion.ToString())
        Trace.WriteLine("Computer name: " & System.Environment.MachineName)
        Trace.WriteLine("User name: " & System.Environment.UserName)
        Trace.WriteLine("CLR version: " & System.Environment.Version.ToString)
        Trace.WriteLine("Command line: " & System.Environment.CommandLine)

        ' Enumerate the trace listener collection and  
        ' display details about each configured trace listener.
        Trace.WriteLine("Number of configured trace listeners = " & _
            Trace.Listeners.Count.ToString())

        Dim tl As TraceListener
        For Each tl In Trace.Listeners
            Trace.WriteLine("Trace listener name = " & tl.Name)
            Trace.WriteLine("               type = " & tl.GetType().ToString())
        Next tl

        Trace.Unindent()
        Trace.WriteLine(DateTime.Now.ToString() & " - End of " & methodName)
        Trace.Unindent()

    End Sub 

    ' Define the main entry point of this class. 
    ' The main method adds a console trace listener to the collection 
    ' of configured trace listeners, then writes details on the current 
    ' executing environment. 
    Public Shared Sub Main(ByVal CmdArgs() As String)

        ' Write a trace message to all configured trace listeners.
        Trace.WriteLine(DateTime.Now.ToString() & " - Start of Main")

        ' Define a trace listener to direct trace output from this method 
        ' to the console. 
        Dim consoleTracer As ConsoleTraceListener

        ' Check the command line arguments to determine which 
        ' console stream should be used for trace output. 
        If (CmdArgs.Length > 0) AndAlso _
           (CmdArgs(0).ToLower.Equals("/stderr")) Then 
            ' Initialize the console trace listener to write 
            ' trace output to the standard error stream.
            consoleTracer = New ConsoleTraceListener(True)
        Else 
            ' Initialize the console trace listener to write 
            ' trace output to the standard output stream.
            consoleTracer = New ConsoleTraceListener
        End If 
        ' Set the name of the trace listener, which helps identify this  
        ' particular instance within the trace listener collection.
        consoleTracer.Name = "mainConsoleTracer" 

        ' Write the initial trace message to the console trace listener.
        consoleTracer.WriteLine(DateTime.Now.ToString() & " [" & _
             consoleTracer.Name & "] - Starting output to trace listener.")

        ' Add the new console trace listener to  
        ' the collection of trace listeners.
        Trace.Listeners.Add(consoleTracer)

        ' Call a local method, which writes information about the current  
        ' execution environment to the configured trace listeners.
        WriteEnvironmentInfoToTrace()

        ' Write the final trace message to the console trace listener.
        consoleTracer.WriteLine(DateTime.Now.ToString() & " [" & _
            consoleTracer.Name & "] - Ending output to trace listener.")

        ' Flush any pending trace messages, remove the  
        ' console trace listener from the collection, 
        ' and close the console trace listener.
        Trace.Flush()
        Trace.Listeners.Remove(consoleTracer)
        consoleTracer.Close()

        ' Write a final trace message to all trace listeners.
        Trace.WriteLine(DateTime.Now.ToString() + " - End of Main")

        ' Close all other configured trace listeners.
        Trace.Close()

    End Sub 

End Class
// Define the TRACE directive, which enables trace output to the  
// Trace.Listeners collection. Typically, this directive is defined 
// as a compilation argument.
#define TRACE
using System;
using System.Diagnostics;

public class ConsoleTraceSample
{

    // Define a simple method to write details about the current executing  
    // environment to the trace listener collection. 
    public static void WriteEnvironmentInfoToTrace()
    {

        string methodName = "WriteEnvironmentInfoToTrace";

        Trace.Indent();
        Trace.WriteLine(DateTime.Now.ToString() + " - Start of " + methodName);
        Trace.Indent();

        // Write details on the executing environment to the trace output.
        Trace.WriteLine("Operating system: " + System.Environment.OSVersion.ToString());
        Trace.WriteLine("Computer name: " + System.Environment.MachineName);
        Trace.WriteLine("User name: " + System.Environment.UserName);
        Trace.WriteLine("CLR runtime version: " + System.Environment.Version.ToString());
        Trace.WriteLine("Command line: " + System.Environment.CommandLine);

        // Enumerate the trace listener collection and  
        // display details about each configured trace listener.
        Trace.WriteLine("Number of configured trace listeners = " + Trace.Listeners.Count.ToString());

        foreach (TraceListener tl in Trace.Listeners)
        {
            Trace.WriteLine("Trace listener name = " + tl.Name);
            Trace.WriteLine("               type = " + tl.GetType().ToString());
        }

        Trace.Unindent();
        Trace.WriteLine(DateTime.Now.ToString() + " - End of " + methodName);
        Trace.Unindent();

    }

    // Define the main entry point of this class. 
    // The main method adds a console trace listener to the collection 
    // of configured trace listeners, then writes details on the current 
    // executing environment. 
    public static void Main(string[] CmdArgs)
    {

        // Write a trace message to all configured trace listeners.
        Trace.WriteLine(DateTime.Now.ToString()+" - Start of Main");

        // Define a trace listener to direct trace output from this method 
        // to the console.
        ConsoleTraceListener consoleTracer;

        // Check the command line arguments to determine which 
        // console stream should be used for trace output. 
        if ((CmdArgs.Length>0)&&(CmdArgs[0].ToString().ToLower().Equals("/stderr")))
            // Initialize the console trace listener to write 
            // trace output to the standard error stream.
        {
            consoleTracer = new ConsoleTraceListener(true);
        }
        else
        {
            // Initialize the console trace listener to write 
            // trace output to the standard output stream.
            consoleTracer = new ConsoleTraceListener();
        }
        // Set the name of the trace listener, which helps identify this  
        // particular instance within the trace listener collection.
        consoleTracer.Name = "mainConsoleTracer";

        // Write the initial trace message to the console trace listener.
        consoleTracer.WriteLine(DateTime.Now.ToString()+" ["+consoleTracer.Name+"] - Starting output to trace listener.");

        // Add the new console trace listener to  
        // the collection of trace listeners.
        Trace.Listeners.Add(consoleTracer);

        // Call a local method, which writes information about the current  
        // execution environment to the configured trace listeners.
        WriteEnvironmentInfoToTrace();

        // Write the final trace message to the console trace listener.
        consoleTracer.WriteLine(DateTime.Now.ToString()+" ["+consoleTracer.Name+"] - Ending output to trace listener.");

        // Flush any pending trace messages, remove the  
        // console trace listener from the collection, 
        // and close the console trace listener.
        Trace.Flush();
        Trace.Listeners.Remove(consoleTracer);
        consoleTracer.Close();

        // Write a final trace message to all trace listeners.
        Trace.WriteLine(DateTime.Now.ToString()+" - End of Main");

        // Close all other configured trace listeners.
        Trace.Close();

    }

}
Version Information

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.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.