Event Log Sample

This sample demonstrates how to create and delete event logs, and how to read and write to system event logs and custom event logs.

Visual Basic offers two different logging mechanisms:

  • The EventLog component, used in this sample, provides access to the operating system event logs. You can add and delete logs, add and remove event log sources, write messages, and delete messages.

  • The My.Application.Log object also provides access to some of the EventLog features. In addition, My.Application.Log has features that enable you to write messages to text files. For more information, see Logging Sample and Logging Information from the Application.

To get samples and instructions for installing them

  • Do one or more of the following:

    • On the Help menu, click Samples.

      The Readme displays information about samples.

    • Visit the Visual Studio 2008 Samples Web site. The most recent versions of samples are available there.

    • Locate samples on the computer on which Visual Studio is installed. By default, samples and a Readme file are installed in drive:\Program Files\Microsoft Visual Studio 9.0\Samples\lcid. For Express editions of Visual Studio, all samples are located online.

For more information, see Visual Studio Samples.

Security noteSecurity Note:

This sample code is intended to illustrate a concept, and it shows only the code that is relevant to that concept. It may not meet the security requirements for a specific environment, and it should not be used exactly as shown. We recommend that you add security and error-handling code to make your projects more secure and robust. Microsoft provides this sample code "AS IS" with no warranties.

To run this sample

  • Press F5.

    Not all operating systems support event logs. For more information, see EventLog.


The main form, Form1, contains three Button controls to read, write, and create or delete event logs. Each opens a new form that collects information specific to the operation.

The form WriteForm collects the text, ID, and type for an event-log entry and writes the entry to the Application event log using the WriteEntry method.

The form ReadForm fills a ListBox control with the names of the event logs on the computer. The list is obtained by calling the GetEventLogs method, and then displaying the value of the LogDisplayName property for each log. The last ten entries of the selected log are retrieved with Entries property and then displayed in a RichTextBox control.

The form CreateDeleteForm calls the CreateEventSource and Delete methods. The SourceExists method is used to verify that the event log and source do not already exist before creating them. The Exists method is used to verify that the event log exists before deleting it.

See Also


Logging Sample


Introduction to the EventLog Component

Logging Information from the Application