How Do I...Monitor an event log?

Event logging provides a standard, centralized way for you to have your applications record important software and hardware events. Windows supplies a standard user interface for viewing the logs (Event Log). Using the common language runtime's EventLog component, you can easily connect to existing event logs on both local and remote computers, and receive event notifications when a new entry is written to the log.

This sample illustrates how to monitor an event log for new entries. It is a small console application that can be run from a command prompt. The application takes two command line arguments. The first argument is the name of the log that you want to monitor. The second argument, which is optional, allows you to specify the machine name of the server on which the log resides.

Try running the sample as follows:

> LogMonitor.exe Application

Now run the LogWrite.exe sample and write a new entry to the application log. You will see that the LogMonitor is being notified about the new entry being written.

In its simplest form, monitoring an event log involves:

  1. Creating a new instance of an EventLog component and pointing it to a appropriate event log:

    
    Dim log, machine As String
    ...
    Dim aLog As New EventLog
    aLog.Log = log
    aLog.MachineName = machine
    
    VB

  2. Adding an event handler:

    
    AddHandler aLog.EntryWritten, AddressOf OnEntryWritten
    
    VB

  3. Handling the event notification in your event handler:

    
    Sub OnEntryWritten(ByVal source As Object, ByVal e As EventLogEvent)
        Console.WriteLine("Written: " + e.Entry.Message)
    End Sub
    
    VB

Example

 
VB LogMonitor.exe

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.