Listing 1: Writing Trace Output to the Console
Option Explicit On
Option Strict On
Imports System.Diagnostics
Module Tracing
Sub Main()
Dim consoleListener As New TextWriterTraceListener(Console.Out)
Trace.Listeners.Add(consoleListener)
Trace.WriteLine("Trace message")
End Sub
End Module
Listing 2: Custom TraceListener
Option Explicit On
Option Strict On
Imports System.Diagnostics
Imports System.IO
Imports System.Reflection.Assembly
Public Class AppTracer
Inherits System.Diagnostics.TraceListener
Private _file As StreamWriter = Nothing
'Public constructor. Create the file to log to
Public Sub New()
Dim logFileName As String = _
Left(GetEntryAssembly.Location, _
GetEntryAssembly.Location.LastIndexOf(".") + 1) + _
"log" _file = New StreamWriter(logFileName, True)
'Write out the starting record
_file.WriteLine(String.Format(ControlChars.CrLf + _
"----- Trace Start {0} -----", Date.Now))
End Sub
'Write the entry to the log file
Public Overloads Overrides Sub Write(ByVal entry As String)
_file.Write(entry)
End Sub
'WriteLine the entry to the log file
Public Overloads Overrides Sub WriteLine(ByVal entry As String)
_file.WriteLine(entry)
End Sub
'Flush any output to the file
Public Overrides Sub Flush()
If Not (_file Is Nothing) Then
_file.Flush()
End If
End Sub
'Flush any output and close the file
Public Overrides Sub Close()
If _file Is Nothing Then Exit Sub
_file.WriteLine(String.Format("----- Trace End {0} -----" + _
ControlChars.CrLf, Date.Now))
Flush()
_file.Close()
_file = Nothing
End Sub
Listing 3: Completed Program
Option Explicit On
Option Strict On
Imports System.Diagnostics
Module Tracing
Private logToConsole As New BooleanSwitch _
("controlTracing", "Do trace messages go to the console")
Private conditionalLogging As New TraceSwitch _
("variableTracing", "Use a trace switch")
Sub Main()
If logToConsole.Enabled Then
Dim consoleListener As New TextWriterTraceListener(Console.Out)
Trace.Listeners.Add(consoleListener)
Trace.WriteLine("Trace message")
End If
Dim customListener As New AppTracer
Trace.Listeners.Add(customListener)
Trace.WriteLine("Writes to console and file")
Dim eventListener As New EventLogTraceListener("myEventLog")
Trace.Listeners.Add(eventListener)
Trace.WriteLineIf(conditionalLogging.TraceVerbose, _
"Log if logging verbose")
customListener.Close()
End Sub
End Module