Windows Event Log

The Windows event log provides a centralized, remotely accessible mechanism for the operating system and applications to log events. By default, the event log contains three separate logs: Application, System, and Security.

Access to the event log is exposed through the System.Diagnostics.EventLog class. EventLog provides a mixture of static and instance members used to read from and write to the event log as well as create, delete, and clear individual logs.

Writing to the Event Log

Registering an Event Source

Before an application can write to the event log, an event source must be configured and registered against a particular log; a source is a string that uniquely identifies a component and is usually the application name.

A source can be registered with only one log at a time; attempting to register a source against multiple logs results in a System.ArgumentException being thrown.

Sources can be registered using the static EventLog.CreateEventSource method, which offers the following two overloads:

void CreateEventSource(String source, String log);
void CreateEventSource(String source, String log, String machine);

The first overload takes a source name and the name of the log to register the source against. If null or an empty string is provided, the log argument defaults to Application.

The second overload takes a computer name; this permits events to be written to the event log of a remote machine. Specifying a dot () as the computer name uses the local event log and is equivalent to using the first overload. The following statements demonstrate the use of the CreateEventSource method:

// Register the "myApp" source against the local
// "Application" log
EventLog.CreateEventSource("myApp", "Application");

// Equivalent to the above statement; "." is the local machine
// and the "Application" log is the default log.
EventLog.CreateEventSource("myApp",null,".");

// Register against "SomeLog" log of a
// remote machine called "myMachine"
EventLog.CreateEventSource("myApp","SomeLog","myMachine");

Event sources are manually deregistered using the static EventLog.Delete-EventSource method or automatically if a log is deleted; deleting logs is discussed later in this section.

Writing Events

Entries are written to the event log using the EventLog.WriteEntry method; WriteEntry offers a choice of ten instance and static overloads. The static methods of EventLog mirror the instance methods but take an extra argument that identifies the event source. Instance methods use the source specified in the EventLog.Source property; an exception is thrown if the Source property isn’t set when WriteEntry is called.

When WriteEntry is called, an entry is made to the log that the source is registered against. If the source of a WriteEntry call isn’t already registered against a log, it’s automatically registered; static WriteEntry overloads register the source against the Application log, whereas instance overloads use the log specified by the EventLog.Log property. If the Source and Log properties don’t match the configured source/log registration settings when WriteEntry is called, an ArgumentException is thrown.

The arguments that can be passed to the various overloaded versions of WriteEntry are summarized in Table A-8.

Table A-8. Arguments of the EventLog.WriteEntry() Overloaded Method

Argument

Comments

message

The text of the event to write to the event log.

type

A value from the EventLogEntryType enumeration identifying the type of event. Valid values include Error, Warning, Information, SuccessAudit, and FailureAudit.

 

The SuccessAudit and FailureAudit values are used only for security events.

eventID

An application-specific event identifier.

category

An application-specific category identifier.

rawData

A byte array that holds binary data associated with the event.

The following example program periodically writes an entry to the Application log with the source name MyApp:

using System;
using System.Diagnostics;
using System.Threading;

public class EventLogWriter {

    public static void Main(String[] args) {

        // Create the EventLog instance and open the
        // "Application" log
        EventLog log = new EventLog("Application", ".", "MyApp");

        // Loop and write an entry every 5 seconds
        while (true) {
            log.WriteEntry("Test Message",
                EventLogEntryType.Error, 200);
            Thread.Sleep(5000);
        }
    }
}

Reading from the Event Log

Although applications are more likely to write to than read the event log, sometimes an application will read the event log. The EventLog.Entries property returns an EventLogEntryCollection containing EventLogEntry instances. Each EventLogEntry represents a single event log record and provides the properties detailed in Table A-9 to access the details of the event.

Table A-9. EventLogEntry Properties

Property

Description

Category

Gets the text associated with the CategoryNumber of the entry.

CategoryNumber

Gets the category number of the entry.

Data

Gets the binary data associated with the entry.

EntryType

Gets the event type of the entry. The returned value is a member of the EventLogEntryType enumeration; valid values are Error, Warning, Information, SuccessAudit, and FailureAudit.

EventID

Gets the application-specific event ID for the entry.

Index

Gets the index of the entry in the event log.

MachineName

Gets the name of the machine on which the entry was generated.

Message

Gets the message associated with the entry.

Source

Gets the source associated with the entry.

TimeGenerated

Gets the local time at which the entry was generated.

TimeWritten

Gets the local time at which the entry was written.

UserName

Gets the name of the user responsible for logging the entry.

When an application reads from a log, the Source doesn’t need to be specified; only the Log and MachineName properties are required. Changing the Log and MachineName properties of an existing EventLog instance provides access to the newly specified log.

The following example opens the Application log on the local machine and counts the events generated by the source MyApp:

using System;
using System.Diagnostics;

public class EventLogReader {

    public static void Main() {

        // Create the EventLog instance and open the
        // "Application" log
        EventLog log = new EventLog("Application");

        // Get the collection of log entries
        EventLogEntryCollection entries = log.Entries;

        // Declare a counter
        int count = 0;

        // Loop through the entries and count occurrences for
        // the "MyApp" source
        foreach (EventLogEntry entry in entries) {
            if (entry.Source == "MyApp") count++;
        }

        // Display count information for the source to the console
        Console.WriteLine("Logged events for MyApp = {0}", count);
    }
}

Creating and Deleting Custom Logs

There is no method to explicitly create a new log; if a source is registered against a log that doesn’t exist, calls to the WriteEntry method will cause the log to be created automatically. The following statements show two distinct approaches to creating the MyApplicationLog log using a source named MySrc (assuming the log doesn’t already exist):

// Using an EventLog instance
EventLog e = new EventLog("MyApplicationLog", ".", "MySrc");
e.WriteEntry("A test message");

// Using EventLog static methods
EventLog.CreateEventSource("MySrc", "MyApplicationLog");
EventLog.WriteEntry("MySrc", "A test message");

The existence of a log is determined using the static EventLog.Exists method, passing it a String argument containing the name of the log to test for. An overloaded version also accepts a machine name for testing the existence of a log on a remote machine.

The static EventLog.Delete method accepts the same arguments as Exists but deletes the specified log if it exists; if the log doesn’t exist, a System.SystemException is thrown.

Event Log Notifications

Applications can use the EventLog.EntryWritten event to be notified when entries are written to the event log of the local computer; notifications from remote computers are not supported.

First an EventLog instance is created and mapped to a specific log. Second the EnableRaisingEvents property is set to true; this enables event notifications on the EventLog instance. Finally the EventLog.EntryWritten event is provided with an event handler delegate to be notified when event log entries are written. The delegate that defines the EntryWritten event handler has the following signature:

public delegate void EntryWrittenEventHandler(object sender,
    EntryWrittenEventArgs e);

The sender argument is the EventLog instance that raised the event, and e is a System.Diagnostics.EntryWrittenEventArgs instance; EntryWrittenEventArgs contains an Entry property that gets an EventLogEntry representing the event log entry that caused the event to be raised.

The following example program listens to the Application event log and displays summary details to the console each time an entry is written:

using System;
using System.Diagnostics;

public class EventLoglListener {

    public static void Main() {

        // Create the EventLog instance and open the
        // "Application" log
        EventLog log = new EventLog("Application",
            ".", "testapp");

        // Enable event notifications
        log.EnableRaisingEvents = true;

        // Create the event handler
        log.EntryWritten +=
            new EntryWrittenEventHandler(EventLogEventHandler);

        // Make sure the process does not terminate
        Console.ReadLine();
    }

    public static void EventLogEventHandler(object sender,
           EntryWrittenEventArgs arg) {
        // Get the EventLogEntry that triggered the event
        EventLogEntry entry = arg.Entry;

        // Display summary information for the event to
        // the console
        Console.WriteLine(
            "{0}:Category {1} event triggered by {2}",
            entry.TimeWritten, entry.CategoryNumber,
            entry.Source);
    }
}

If we run the previous EventLogWriter example while the EventLogListener example is running, we get output similar to the following:

02/04/2002 15:04:06:Category 0 event triggered by MyApp
02/04/2002 15:04:11:Category 0 event triggered by MyApp
02/04/2002 15:04:16:Category 0 event triggered by MyApp
02/04/2002 15:04:21:Category 0 event triggered by MyApp
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset