How Do I...Write to an event log?

Event logging provides a standard, centralized way for your applications to record important software and hardware events. Windows supplies a standard user interface for viewing the logs (the Event Viewer). Using the common language runtime's EventLog component, you can easily connect to existing event logs on both local and remote computers, and write entries to these logs. You can also read entries from existing logs and create your own custom event logs.

This sample illustrates how to write to an event log. It's a small console application that can be run from a command prompt. The application takes three command line arguments. The first argument is the log to which the application will write. The second is the message to be written. The third is the name of the source of the event log entry (message).

Try running the sample as follows:

> LogWrite.exe MyLog "Hello World!" "LogWrite Sample"

Now, open the event log viewer and observe that there is a new log added to the list of logs on your machine. The log's name is "MyLog"and it contains an entry written by "LogWrite Sample" (source). Double-click on the entry. It will greet you with a "Hello World!" message.

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

  1. Registering an event source (if not already registered):

    
    If (Not EventLog.SourceExists(source)) Then
        EventLog.CreateEventSource(source, log)
    End If
    
    VB

  2. Creating a new instance of an EventLog component and setting its Source property:

    
    Dim aLog As New EventLog
    aLog.Source = source
    
    VB

  3. Calling the WriteEntry method:

    
    Dim message As String = "some message"
    aLog.WriteEntry(message, EventLogEntryType.Information)
    
    VB

Now, you may want to try to modify the sample so it writes error log entries instead of informational entries. Just change the EventLogEntryType.Information to EventLogEntryType.Error, rebuild the sample and run it again.

Example

 
VB LogWrite.exe

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.