19.5 Event Logs
Useful as the Debug and Trace
classes are, the Win32 platform already provides a logging mechanism
in the form of the event log. Classes are provided in the
System.Diagnostics namespace that allow
applications to enumerate the existing event sources and logs, read
from and write to an event log manually, use an event log as a
backing store for Trace or
Debug output, create and install new event
sources, and monitor an event log for changes.
19.5.1 Reading the Event Log
To read an event log, create an instance of the
EventLog class with the name of the log you wish
to access, and optionally the name of the machine on which the log
resides and the event source with which to filter the log entries.
Once you have a valid EventLog instance, it
provides a wealth of properties and methods that let you examine and
manipulate the log as a whole. To read the individual entries in the
log, use the EventLog.Entries property to retrieve
a collection of EventLogEntry instances. The
following sample displays information on any log on your system:
// DumpLog.cs - use DumpLog <logname>
using System;
using System.Diagnostics;
class DumpLog {
static void Main(string[ ] args) {
// Present the alternatives
if (args.Length <= 0) {
EventLog[ ] ela = EventLog.GetEventLogs( );
Console.WriteLine("Usage: DumpLog <logname>");
Console.WriteLine("\n\tWhere <logname> is one of:\n");
foreach (EventLog el in ela) {
Console.WriteLine("\t{0}", el.LogDisplayName);
}
return;
}
// Extract the parameters
string logName = args[0];
// Check the log actually exists
if (!EventLog.Exists(logName)) {
Console.WriteLine("Unknown log name {0}", logName);
return;
}
// Iterate over the entire log, dumping the events
EventLog el = new EventLog(logName);
Console.WriteLine("{0} on {1}", el.LogDisplayName, el.MachineName);
EventLogEntryCollection elec = el.Entries;
foreach (EventLogEntry ele in elec) {
Console.WriteLine("Event ID {0} ({1}):{2}",
ele.EventID, ele.EntryType, ele.Message);
Console.WriteLine(" generated by {0} on {1} for {2}@{3}",
ele.Source, ele.TimeGenerated, ele.UserName, ele.MachineName);
}
}
}
19.5.2 Writing to the Event Log
Similarly, one can write to
the event log using the
same EventLog class used in the previous example.
The only complexity arises because log entries need a source—if
the event source doesn't already exist, you need to
create it. As the following sample demonstrates, creating a
command-line utility to add events to an event log on the local
machine is trivial:
// WriteLog.cs - use WriteLog <logname> <message>
using System;
using System.Diagnostics;
class WriteLog {
const string SOURCE = "CSiaN";
static void Main(string[ ] args) {
// Extract the parameters
string logName = args[0], message = args[1];
// Verify the log actually exists
if (!EventLog.Exists(logName)) {
Console.WriteLine("Unknown log name '{0}'", logName);
return;
}
// Create the CSiaN event source if necessary
if (!EventLog.SourceExists(SOURCE) ) {
EventLog.CreateEventSource(SOURCE, logName);
}
// Write the event to the log on the local machine
EventLog el = new EventLog(logName, ".", SOURCE);
el.WriteEntry(message)
}
}
19.5.3 Monitoring the Event Log
In some cases it can be useful to
monitor the event log, examining new entries as
they are written and taking appropriate action. To do this, register
a listener for the EventLog.EntryWritten event on
a log we are interested in monitoring. As new event log entries are
added to the log, you receive callbacks, and can access the details
of the new event log entry and take appropriate action. The following
sample demonstrates registering a listener to display new events in a
log as they are written. (To generate new events in the log, use the
preceding WriteLog sample.)
// WatchLog.cs - use WatchLog <logname>
using System;
using System.Diagnostics;
class WatchLog {
static void NewEntryCallback(object o, EntryWrittenEventArgs ewea) {
// The new entry is included in the event arguments
EventLogEntry ele = ewea.Entry;
Console.WriteLine("New event in log: {0}", ele.Message);
}
static void Main(string[ ] args) {
// Check the arguments and provide help
if (args.Length != 1) {
Console.WriteLine("Usage: WatchLog <logname>");
return;
}
// Verify the log actually exists
string logName = args[0];
if (!EventLog.Exists(logName)) {
Console.WriteLine("Unknown log name '{0}'", logName);
return;
}
// Register handler and wait for keypress
EventLog el = new EventLog(logName);
el.EntryWritten += new EntryWrittenEventHandler(NewEntryCallback);
el.EnableRaisingEvents = true;
Console.WriteLine("Listening for events - press <enter> to end");
Console.ReadLine( );
}
}
|