Export (0) Print
Expand All
0 out of 2 rated this helpful - Rate this topic

ConsoleTraceListener Class

Note: This class is new in the .NET Framework version 2.0.

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

Namespace: System.Diagnostics
Assembly: System (in system.dll)

public class ConsoleTraceListener : TextWriterTraceListener
public class ConsoleTraceListener extends TextWriterTraceListener
public class ConsoleTraceListener extends TextWriterTraceListener
NoteNote

The HostProtectionAttribute attribute applied to this class 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.

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

When trace and debugging output is enabled, the ConsoleTraceListener messages are written to the specified System.Console stream, which is similar to the way messages are written with the System.Console.Write or System.Console.WriteLine methods. In a console application, the System.Console output and error streams write messages to the existing console window, or you can redirect the streams to write to a System.IO.TextWriter 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 System.Diagnostics.Trace.Write or System.Diagnostics.Trace.WriteLine 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.Diagnostics.Debug and System.Diagnostics.Trace 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>.

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

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

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.