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)

Inheritance Hierarchy
SystemObject
   SystemMarshalByRefObject
     System.DiagnosticsTraceListener
       System.DiagnosticsTextWriterTraceListener
        System.DiagnosticsConsoleTraceListener

Syntax
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true)]
public class ConsoleTraceListener : TextWriterTraceListener
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true)]
public ref class ConsoleTraceListener : TextWriterTraceListener
[<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true)>]
type ConsoleTraceListener = 
    class
        inherit TextWriterTraceListener
    end
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True)>
Public Class ConsoleTraceListener
	Inherits TextWriterTraceListener
Constructors
NameDescription
System_CAPS_pubmethod ConsoleTraceListener

Initializes a new instance of the ConsoleTraceListener class with trace output written to the standard output stream.

System_CAPS_pubmethod ConsoleTraceListener

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.

Properties
NameDescription
System_CAPS_pubproperty

Gets the custom trace listener attributes defined in the application configuration file.(Inherited from TraceListener.)

System_CAPS_pubproperty

Gets and sets the trace filter for the trace listener.(Inherited from TraceListener.)

System_CAPS_pubproperty

Gets or sets the indent level.(Inherited from TraceListener.)

System_CAPS_pubproperty

Gets or sets the number of spaces in an indent.(Inherited from TraceListener.)

System_CAPS_pubproperty

Gets a value indicating whether the trace listener is thread safe. (Inherited from TraceListener.)

System_CAPS_pubproperty

Gets or sets a name for this TraceListener.(Inherited from TraceListener.)

System_CAPS_protproperty

Gets or sets a value indicating whether to indent the output.(Inherited from TraceListener.)

System_CAPS_pubproperty

Gets or sets the trace output options.(Inherited from TraceListener.)

System_CAPS_pubproperty

Gets or sets the text writer that receives the tracing or debugging output.(Inherited from TextWriterTraceListener.)

Methods
NameDescription
System_CAPS_pubmethod Close

Closes the output to the stream specified for this trace listener.(Overrides TextWriterTraceListenerClose.)

System_CAPS_pubmethod CreateObjRef

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethod Dispose

Releases all resources used by the TraceListener.(Inherited from TraceListener.)

System_CAPS_protmethod Dispose

This API supports the product infrastructure and is not intended to be used directly from your code. Disposes this TextWriterTraceListener object.(Inherited from TextWriterTraceListener.)

System_CAPS_pubmethod Equals

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_pubmethod Fail

Emits an error message to the listener you create when you implement the TraceListener class.(Inherited from TraceListener.)

System_CAPS_pubmethod Fail

Emits an error message and a detailed error message to the listener you create when you implement the TraceListener class.(Inherited from TraceListener.)

System_CAPS_protmethod Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethod Flush

Flushes the output buffer for the .(Inherited from TextWriterTraceListener.)

System_CAPS_pubmethod GetHashCode

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethod GetLifetimeService

Retrieves the current lifetime service object that controls the lifetime policy for this instance.(Inherited from MarshalByRefObject.)

System_CAPS_protmethod GetSupportedAttributes

Gets the custom attributes supported by the trace listener.(Inherited from TraceListener.)

System_CAPS_pubmethod GetType

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethod InitializeLifetimeService

Obtains a lifetime service object to control the lifetime policy for this instance.(Inherited from MarshalByRefObject.)

System_CAPS_protmethod MemberwiseClone

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_protmethod MemberwiseClone

Creates a shallow copy of the current MarshalByRefObject object.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethod ToString

Returns a string that represents the current object.(Inherited from Object.)

System_CAPS_pubmethod TraceData

Writes trace information, a data object and event information to the listener specific output.(Inherited from TraceListener.)

System_CAPS_pubmethod TraceData

Writes trace information, an array of data objects and event information to the listener specific output.(Inherited from TraceListener.)

System_CAPS_pubmethod TraceEvent

Writes trace and event information to the listener specific output.(Inherited from TraceListener.)

System_CAPS_pubmethod TraceEvent

Writes trace information, a message, and event information to the listener specific output.(Inherited from TraceListener.)

System_CAPS_pubmethod TraceEvent

Writes trace information, a formatted array of objects and event information to the listener specific output.(Inherited from TraceListener.)

System_CAPS_pubmethod TraceTransfer

Writes trace information, a message, a related activity identity and event information to the listener specific output.(Inherited from TraceListener.)

System_CAPS_pubmethod Write

Writes the value of the object's ToString method to the listener you create when you implement the TraceListener class.(Inherited from TraceListener.)

System_CAPS_pubmethod Write

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.)

System_CAPS_pubmethod Write

Writes a message to this instance's .(Inherited from TextWriterTraceListener.)

System_CAPS_pubmethod Write

Writes a category name and a message to the listener you create when you implement the TraceListener class.(Inherited from TraceListener.)

System_CAPS_protmethod WriteIndent

Writes the indent to the listener you create when you implement this class, and resets the property to false.(Inherited from TraceListener.)

System_CAPS_pubmethod WriteLine

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.)

System_CAPS_pubmethod WriteLine

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.)

System_CAPS_pubmethod WriteLine

Writes a message to this instance's followed by a line terminator. The default line terminator is a carriage return followed by a line feed (\r\n).(Inherited from TextWriterTraceListener.)

System_CAPS_pubmethod WriteLine

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.)

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 stream or to the stream.

System_CAPS_importantImportant

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.

System_CAPS_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 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.

System_CAPS_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:DEBUGflag 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 collection in your code, or you can add a ConsoleTraceListener object to the 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 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 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 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>.

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 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();

    }

}
' 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
Version Information
.NET Framework
Available since 2.0
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.

Return to top