ConsoleTraceListener 类  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将跟踪或调试输出指引至标准输出或标准错误流。
public ref class ConsoleTraceListener : System::Diagnostics::TextWriterTraceListenerpublic class ConsoleTraceListener : System.Diagnostics.TextWriterTraceListenertype ConsoleTraceListener = class
    inherit TextWriterTraceListenerPublic Class ConsoleTraceListener
Inherits TextWriterTraceListener- 继承
示例
下面的代码示例实现一个控制台应用程序,该应用程序由具有两个公共方法的类组成。
方法 Main 检查命令行参数,并确定跟踪输出应定向到标准错误流还是标准输出流。 
              Main为指定的Console输出流创建并初始化 ConsoleTraceListener 对象,并将此对象添加到跟踪侦听器集合。 然后, WriteEnvironmentInfoToTrace 它调用 方法,该方法将有关执行环境和跟踪侦听器配置的详细信息写入跟踪输出。
当示例应用程序运行时,环境和跟踪配置详细信息将通过 ConsoleTraceListener 对象写入指定的控制台输出流。
// 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
注解
ConsoleTraceListener使用 类将跟踪和调试消息写入控制台。 可以初始化 对象以 ConsoleTraceListener 将跟踪消息 Console.Out 写入流或 Console.Error 流。
重要
此类型实现 IDisposable 接口。 在使用完类型后,您应直接或间接释放类型。 若要直接释放类型,请在 块中try/catch调用其 Dispose 方法。 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。 有关详细信息,请参阅 IDisposable 接口主题中的“使用实现 IDisposable 的对象”一节。
启用跟踪和调试输出后, ConsoleTraceListener 会将消息写入指定的 System.Console 流,这类似于使用 Console.Write 或 Console.WriteLine 方法写入消息的方式。 在控制台应用程序中, System.Console 输出和错误流会将消息写入现有控制台窗口,或者你可以重定向流以写入 System.IO.TextWriter 实例。
注意
如果控制台不存在(如在基于 Windows 的应用程序中),则不会显示写入控制台的消息。
ConsoleTraceListener如果希望通过 Trace、 TraceSource或 Debug 写入到控制台的消息,请将 对象添加到相应的Listeners集合。 此外,还可以使用 Trace.Write 或 Trace.WriteLine 方法将消息直接写入控制台。
注意
              Debug和 Trace 类共享相同的TraceListenerCollection集合,通过各自的Listeners属性进行访问。 如果使用其中一个 ConsoleTraceListener 类将对象添加到集合中,另一个类会自动使用相同的侦听器。
大多数编译器通过条件编译标志启用跟踪和调试输出。 如果不启用跟踪或调试,则通过 System.Diagnostics.Debug 和 System.Diagnostics.Trace 类写入的消息实际上将被忽略。 用于启用跟踪和调试输出的语法是编译器特定的;如果使用 C# 或 Visual Basic 以外的编译器,请参阅编译器的文档。
- 若要在 C# 中启用调试,请在编译代码时将 /d:DEBUG标志添加到编译器命令行,也可以将 #define DEBUG 添加到文件顶部。 在 Visual Basic 中,将 /d:DEBUG=True 标志添加到编译器命令行。 
- 若要在 C# 中启用跟踪,请在编译代码时将 /d:TRACE 标志添加到编译器命令行,或将 #define TRACE 添加到文件的顶部。 在 Visual Basic 中,将 /d:TRACE=True 标志添加到编译器命令行。 
可以在代码中将 Listeners 对象添加到ConsoleTraceListener集合中。 或者,对于.NET Framework应用,可以通过应用程序配置文件将 Listeners 对象添加到ConsoleTraceListener集合。 ConsoleTraceListener在代码中添加 对象,以便为特定代码节或执行路径编写消息。 ConsoleTraceListener在应用程序配置文件中添加 对象,以在应用程序执行时将所有跟踪和调试消息定向到控制台。
若要将特定代码部分的跟踪和调试消息写入控制台,请初始化 ConsoleTraceListener 对象并将其添加到 Listeners 集合中。 使用 Trace 或 Debug 类检测包含消息的代码部分。 在代码部分的末尾,从集合中删除 ConsoleTraceListener 对象,并在 上ConsoleTraceListener调用 Close 方法。Listeners
对于.NET Framework应用,若要在应用程序执行时将所有跟踪和调试消息定向到控制台,请将 对象添加到ConsoleTraceListener应用程序配置文件。 以下示例将名为 的对象configConsoleListener添加到 ConsoleTraceListener 集合中Listeners。
<configuration>  
  <system.diagnostics>  
    <trace autoflush="false" indentsize="4">  
      <listeners>  
        <add name="configConsoleListener" type="System.Diagnostics.ConsoleTraceListener" />  
      </listeners>  
    </trace>  
  </system.diagnostics>  
 </configuration>  
有关在应用程序配置文件中添加跟踪侦听器的详细信息,请参阅 <侦听器>。
构造函数
| ConsoleTraceListener() | 初始化 ConsoleTraceListener 类的新实例,并将跟踪输出写入标准输出流中。 | 
| ConsoleTraceListener(Boolean) | 初始化 ConsoleTraceListener 类的一个新实例,并利用一个选项将跟踪输出写入标准输出流或标准错误流中。 | 
属性
| Attributes | 获取应用程序配置文件中定义的自定义跟踪侦听器特性。(继承自 TraceListener) | 
| Filter | 获取或设置跟踪侦听器的跟踪筛选器。(继承自 TraceListener) | 
| IndentLevel | 获取或设置缩进级别。(继承自 TraceListener) | 
| IndentSize | 获取或设置缩进的空格数。(继承自 TraceListener) | 
| IsThreadSafe | 获取一个值,该值指示跟踪侦听器是否是线程安全的。(继承自 TraceListener) | 
| Name | 获取或设置此 TraceListener 的名称。(继承自 TraceListener) | 
| NeedIndent | 获取或设置一个值,该值指示是否缩进输出。(继承自 TraceListener) | 
| TraceOutputOptions | 获取或设置跟踪输出选项。(继承自 TraceListener) | 
| Writer | 获取或设置接收跟踪或调试输出的文本编写器。(继承自 TextWriterTraceListener) |