Application Development Using Visual Basic and .NET By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Appendix B. Tracing and Debugging in .NET
Both the Debug and Trace classes have a static Listeners collection. This collection of TraceListeners represents a list of TraceListener objects that want to receive the output from the Debug or Trace class. Listeners are added to or removed from the collection just as with any other .NET collection.
' Create a listener that writes to the console Dim ConsoleOutput As New TextWriterTraceListener(_ Console.Out, "Console.Out Listener") Trace.Listeners.Add(ConsoleOutput) ' Create a listener that writes to a text file Dim OutputFile As Stream = File.Create("output.txt") Dim OutputFileListener As TextWriterTraceListener = New _ TextWriterTraceListener(OutputFile, _ "Output File Listener") Trace.Listeners.Add(OutputFileListener) ' Show the listeners now ShowListeners() ' Remove the default listener Trace.Listeners.Remove("Default")
In this code extract, the OutputFileListener in the example will send the Trace output to a file called output.txt . The DefaultTraceListener is added automatically to the Listener collections. Any of the listeners, including the default listener, can be removed from the collection by invoking the collection's Remove method. To list all listeners in the collection:
Sub ShowListeners() Console.WriteLine("Trace Listeners:") Dim tr As TraceListener For Each tr In Trace.Listeners Console.WriteLine(" " & tr.Name) Next Console.WriteLine("") End Sub