
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
462
|
Chapter 8: Diagnostics
Solution
Monitoring an event log for a specific entry requires the following steps:
1. Create the following method to set up the event handler to handle event log
writes:
public void WatchForAppEvent(EventLog log)
{
log.EnableRaisingEvents = true;
// Hook up the System.Diagnostics.EntryWrittenEventHandler.
log.EntryWritten += new EntryWrittenEventHandler(OnEntryWritten);
}
2. Create the event handler to examine the log entries and determine whether fur-
ther action is to be performed. For example:
public static void OnEntryWritten(object source,
EntryWrittenEventArgs entryArg)
{
if (entryArg.Entry.EntryType == EventLogEntryType.Error)
{
Console.WriteLine(entryArg.Entry.Message);
Console.WriteLine(entryArg.Entry.Category);
Console.WriteLine(entryArg.Entry.EntryType.ToString( ));
// Do further actions here as necessary...
}
}
Discussion
This recipe revolves around the EntryWrittenEventHandler delegate, which calls
back a method whenever any new entry is written to the event log. The
EntryWrittenEventHandler delegate accepts two arguments: a source of type object
and an entryArg of type EntryWrittenEventArgs. The entryArg parameter is the most
interesting of the two. It contains a property called
Entry that returns an
EventLogEntry object. This EventLogEntry object ...