Redigera

Dela via


ConsoleTraceListener Class

Definition

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

public ref class ConsoleTraceListener : System::Diagnostics::TextWriterTraceListener
public class ConsoleTraceListener : System.Diagnostics.TextWriterTraceListener
type ConsoleTraceListener = class
    inherit TextWriterTraceListener
Public Class ConsoleTraceListener
Inherits TextWriterTraceListener
Inheritance

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

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

Important

This type implements the 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 System.Console stream, which is similar to the way messages are written with the Console.Write or 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.

Note

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 Trace.Write or Trace.WriteLine methods.

Note

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: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 Listeners collection in your code. Or, for .NET Framework apps, 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.

For .NET Framework apps, to direct all trace and debug messages to the console while the application executes, add a ConsoleTraceListener object to the application configuration file. 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>.

Constructors

ConsoleTraceListener()

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

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.

Properties

Attributes

Gets the custom trace listener attributes defined in the application configuration file.

(Inherited from TraceListener)
Filter

Gets or sets the trace filter for the trace listener.

(Inherited from TraceListener)
IndentLevel

Gets or sets the indent level.

(Inherited from TraceListener)
IndentSize

Gets or sets the number of spaces in an indent.

(Inherited from TraceListener)
IsThreadSafe

Gets a value indicating whether the trace listener is thread safe.

(Inherited from TraceListener)
Name

Gets or sets a name for this TraceListener.

(Inherited from TraceListener)
NeedIndent

Gets or sets a value indicating whether to indent the output.

(Inherited from TraceListener)
TraceOutputOptions

Gets or sets the trace output options.

(Inherited from TraceListener)
Writer

Gets or sets the text writer that receives the tracing or debugging output.

(Inherited from TextWriterTraceListener)

Methods

Close()

Closes the output to the stream specified for this trace listener.

Close()

Closes the Writer so that it no longer receives tracing or debugging output.

(Inherited from TextWriterTraceListener)
CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose()

Releases all resources used by the TraceListener.

(Inherited from TraceListener)
Dispose(Boolean)

Disposes this TextWriterTraceListener object.

(Inherited from TextWriterTraceListener)
Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Fail(String)

Emits an error message to the listener you create when you implement the TraceListener class.

(Inherited from TraceListener)
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)
Flush()

Flushes the output buffer for the Writer.

(Inherited from TextWriterTraceListener)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetSupportedAttributes()

Gets the custom attributes supported by the trace listener.

(Inherited from TraceListener)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString()

Returns a string that represents the current object.

(Inherited from Object)
TraceData(TraceEventCache, String, TraceEventType, Int32, Object)

Writes trace information, a data object and event information to the listener specific output.

(Inherited from TraceListener)
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)
TraceEvent(TraceEventCache, String, TraceEventType, Int32)

Writes trace and event information to the listener specific output.

(Inherited from TraceListener)
TraceEvent(TraceEventCache, String, TraceEventType, Int32, String)

Writes trace information, a message, and event information to the listener specific output.

(Inherited from TraceListener)
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)
TraceTransfer(TraceEventCache, String, Int32, String, Guid)

Writes trace information, a message, a related activity identity and event information to the listener specific output.

(Inherited from TraceListener)
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)
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)
Write(String)

Writes a message to this instance's Writer.

(Inherited from TextWriterTraceListener)
Write(String, String)

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

(Inherited from TraceListener)
WriteIndent()

Writes the indent to the listener you create when you implement this class, and resets the NeedIndent property to false.

(Inherited from TraceListener)
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)
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)
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)
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)

Applies to

See also