更新:2007 年 11 月
Debug 和 Trace 类将消息发送给名为侦听器的对象,它们将接收和处理这些消息。当启用跟踪或调试后,将自动创建并初始化这样一个侦听器:DefaultTraceListener。有关更多信息,请参见跟踪侦听器。如果需要将 Trace 或 Debug 输出定向到任何其他信息源,则必须创建并初始化附加的跟踪侦听器。
所创建的侦听器应反映您的具体需要。例如,您可能需要所有跟踪输出的文本记录。在这种情况下,可以创建一个侦听器,使其在启用时将所有输出写入一个新的文本文件。另一方面,您可能只需要在执行应用程序的过程中查看输出。在这种情况下,可以创建一个侦听器,使其将所有输出定向到一个控制台窗口。EventLogTraceListener 可以将跟踪输出定向到一个事件日志,而 TextWriterTraceListener 则可将跟踪输出写至一个流中。
创建和初始化跟踪侦听器
声明您的跟踪侦听器。如果您所创建的特定侦听器需要其他任何对象,则将其声明。下面的示例显示如何创建一个写入文本文件的侦听器:
' Creates the text file that the trace listener will write to. Dim myTraceLog As New System.IO.FileStream("C:\myTraceLog.txt", _ IO.FileMode.OpenOrCreate) ' Creates the new trace listener Dim myListener As New TextWriterTraceListener(myTraceLog)
// Creates the text file that the trace listener will write to. System.IO.FileStream myTraceLog = new System.IO.FileStream("C:\\myTraceLog.txt", System.IO.FileMode.OpenOrCreate); // Creates the new trace listener. System.Diagnostics.TextWriterTraceListener myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog);
发出跟踪输出。
如果要让侦听器接收所有跟踪输出,请将该跟踪侦听器添加到 Listeners 集合中。
下面的示例显示如何将侦听器添加到 Listeners 集合中:
Trace.Listeners.Add(myListener)
System.Diagnostics.Trace.Listeners.Add(myListener);
- 或 -
如果您不想让侦听器接收跟踪输出,则不要将其添加到 Listeners 集合中。您可以通过独立于 Listeners 集合的侦听器来发出输出,方法是调用该侦听器自己的输出方法。下面的示例显示如何将代码行写入不在 Listeners 集合中的侦听器:
myListener.WriteLine( _ "This output will not go to the Listeners collection")
myListener.WriteLine( "This output will not go to the Listeners collection");
如果您的侦听器不是 Listeners 集合的成员,则可能有必要通过调用 Flush 方法来记录输出。
' Flushes the buffers of all listeners in the Listeners collection. Trace.Flush() ' Flushes only the buffer of myListener. myListener.Flush()
// Flushes the buffers of all listeners in the Listeners collection. System.Diagnostics.Trace.Flush(); // Flushes only the buffer of myListener. myListener.Flush();