Visual Basic .NET (and the CLR) define and implement listener interfaces. Listeners are classes that can receive information written using the System.Diagnostics.Trace and System.Diagnostics.Debug objects. Debug and Trace provide advanced debugging capabilities and can broadcast messages to all of the listeners associated with the Trace or Debug objects. For example, if you write Debug.WriteLine, the text passed to WriteLine is sent to all listeners.
The EventLogTraceListener allows you to associate an EventLog with the Trace object. As a result, when you write Trace statements in your application for debugging and testing purposes, those statements will be written to the event log.
Listing 20.2 demonstrates how to associate a specific EventLog object via an EventLogTraceListener with the Trace object.
Listing 20.2 Associate an instance of an EventLog with the Trace object to automatically log Trace statements to an event log
1: Sub Main() 2: Dim EventLog As New EventLog("Application", ".", "WriteToEventLog") 3: Dim Listener As New EventLogTraceListener(EventLog) 4: Trace.Listeners.Add(Listener) 5: Trace.WriteLine(Command()) 6: End Sub
The EventLogTraceListener is constructed with an instance of an EventLog object. The EventLogTraceListener implements the TraceListener interface and takes the responsibility of writing to the event log (created on line 2). The Trace object knows how to communicate with objects that implement the TraceListener interface. The Trace object will send information passed to methods like WriteLine to all the listeners that have been added to the Trace.Listeners collection. Line 5 demonstrates obtaining command-line arguments using the Command function. When line 5 runs, the text returned by the Command function is written to the Application event log.