How Do I...Read from 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 Microsoft .NET Framework's EventLog component, you can easily connect to existing event logs on both local and remote computers, and read entries from these logs programmatically.

This sample illustrates how to enumerate entries in an event log. 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 enumerate. The second argument is optional and allows you to specify the machine name of the server on which the log resides.

Try running the sample as follows:

> LogInfo.exe Application

The sample will list all the entries from the application log. You can try the same with the System, Security, and any other logs residing on your machine.

In its simplest form, writing to an event log involves:

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

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

  2. Enumerating through the Entries collection of the EventLog instance:

    
    For Each entry In alog.Entries
        Console.WriteLine("    Entry: " + entry.Message)
    Next entry
    
    VB

Example

 
VB LogInfo.exe

[Run Sample] | [View Source]


Copyright 2001-2002 Microsoft Corporation. All rights reserved.