
.NET 1.1+Tracing to Event Logs
Using tracing within an application allows its activities to be logged and reviewed later to assist with identifying and resolving bugs. Messages can be sent to various locations, including Windows event logs that can be examined using the Event Viewer.
EventLogTraceListener
When you are developing applications it is useful to include logging functionality. If you encounter bugs, or when test users report issues, the logs can be reviewed and may help you to track down those problems. A simple way of providing logging is via the Debug and Trace classes. These classes allow you to output messages to trace listeners, which control how those messages are outputted. For example, information can easily be sent to the Visual Studio output window or to a text file.
In this article I will describe the use of the EventLogTraceListener class. As the name suggests, this is a trace listener that sends messages to the Windows event logs. These logs can be viewed using the Event Viewer tool that is provided with all versions of Microsoft Windows.
Constructors
When you instantiate an EventLogTraceListener you need to link it to an existing event source. You should register an event source for your application before you log messages to event logs, rather than using existing event sources. This makes it easier to filter the logs in order to find messages that relate to your software. In the sample code we will work with an event source named, "My Sample Event Source".
The class includes three constructors. The first accepts an EventLog object via its single parameter. This is useful if you have already instantiated an EventLog that is linked to your event source. You can see it used in the sample code below:
EventLog log = new EventLog();
log.Log = "Application";
log.Source = "My Sample Event Source";
EventLogTraceListener listener = new EventLogTraceListener(log);
If you do not have an EventLog instance you can create a new trace listener using the event source name, provided as a string argument.
EventLogTraceListener listener = new EventLogTraceListener("My Sample Event Source");
Finally, you can use the default constructor. This initialises a new EventLogTraceListener that is not yet linked to an event log. If you use this option, you must set the event log using the EventLog property before you can log messages.
EventLog log = new EventLog();
log.Log = "Application";
log.Source = "My Sample Event Source";
EventLogTraceListener listener = new EventLogTraceListener();
listener.EventLog = log;
17 December 2011