Share via


How to: Subscribe to Events in an Event Log

You can subscribe to events in an event log so that your application is notified when specific events are published in the event log. This allows you to monitor event logs and perform tasks or send notifications when an event occurs. When you subscribe to receive event notifications, you specify an XPath-based query for a group of events that match a specified query criteria. The query filters events based on event properties. For example, you can subscribe to all level 2 events in a certain event log, or you can subscribe to all the events with an identifier equal to 105.

Example

Description

The following code example uses the System.Diagnostics.Eventing.Reader classes to subscribe to receive event notifications for all the level 2 events from the application event log. When an event is published in the event log that matches this criteria, the description and event ID are displayed for the event. The EventLogQuery class is used to create the query for the events you want to subscribe to. The EventLogWatcher class is then used to create the subscription by setting an event handler method for the EventRecordWritten event. The event handler method is called when an event that matches the query criteria is published to the log.

The following code example follows a series of steps to subscribe to events.

  1. Create an instance of the EventLogQuery class by specifying a query string used to filter events, and the name or location of the event log to subscribe to. For more information about how to find event log names, see How to: Configure and Read Event Log Properties or search for event logs in the Event Viewer tool. For more information about how to create an event query string, see Event Queries and Event XML.

  2. (Optional) To subscribe to events on a remote computer, set the Session property to an instance of the EventLogSession class and specify the remote computer name, domain, and the user name and password used to connect to the remote computer.

  3. Create a new EventLogWatcher instance by passing in the EventLogQuery instance created in Step 1 to the EventLogWatcher constructor.

  4. Create a callback method that will execute when an event is reported to the subscription. This method should accept arguments of type Object and EventRecordWrittenEventArgs.

  5. Set the EventRecordWritten event handler to a new event handler that points to the callback method created in Step 4.

  6. Set the Enabled property equal to true to start the event subscription and false to stop the event subscription.

Code

Imports System
Imports System.Diagnostics.Eventing.Reader

Public Class SubscribeToEventsExample

    Public Sub New()

        Dim watcher As EventLogWatcher
        watcher = Nothing

        Try

            ' Subscribe to receive event notifications
            ' in the Application log. The query specifies
            ' that only level 2 events will be returned.
            Dim subscriptionQuery As New EventLogQuery( _
                "Application", PathType.LogName, "*[System/Level=2]")

            watcher = New EventLogWatcher(subscriptionQuery)

            ' Set watcher to listen for the EventRecordWritten
            ' event.  When this event happens, the callback method
            ' (EventLogEventRead) will be called.
            AddHandler watcher.EventRecordWritten, _
                AddressOf Me.HandleEvent

            ' Begin subscribing to events the events
            watcher.Enabled = True
            Console.WriteLine("Waiting for events...")

            Dim i As Integer
            For i = 0 To 4
                If i < 5 Then
                    ' Wait for events to occur. 
                    System.Threading.Thread.Sleep(1000)
                End If
            Next

        Catch e As EventLogReadingException

            Console.WriteLine("Error reading the log: {0}", e.Message)

        Finally

            ' Stop listening to events
            watcher.Enabled = False

            If Not watcher Is Nothing Then
                watcher.Dispose()
            End If

        End Try
    End Sub

    ' <summary>
    ' Callback method that gets executed when an event is
    ' reported to the subscription.
    ' </summary>
    Public Sub HandleEvent(ByVal obj As Object, _
        ByVal arg As EventRecordWrittenEventArgs)

        ' Make sure there was no error reading the event.
        If Not arg.EventRecord Is Nothing Then

            Console.WriteLine("Received event {0} from the subscription.", _
               arg.EventRecord.Id)
            Console.WriteLine("Description: {0}", arg.EventRecord.FormatDescription())
        Else

            Console.WriteLine("The event instance was null.")
        End If
    End Sub

    Public Overloads Shared Function Main( _
    ByVal args() As String) As Integer

        ' Start the event watcher
        Dim eventWatcher As New SubscribeToEventsExample

        Return 0

    End Function
End Class
using System;
using System.Diagnostics.Eventing.Reader;

class SubscribeToEventsExample
{
    static void Main(string[] args)
    {
        EventLogWatcher watcher = null;

        try
        {
            // Subscribe to receive event notifications
            // in the Application log. The query specifies
            // that only level 2 events will be returned.
            EventLogQuery subscriptionQuery = new EventLogQuery(
                "Application", PathType.LogName, "*[System/Level=2]");

            watcher = new EventLogWatcher(subscriptionQuery);

            // Set watcher to listen for the EventRecordWritten
            // event.  When this event happens, the callback method
            // (EventLogEventRead) will be called.
            watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(
                    EventLogEventRead);

            // Begin subscribing to events the events
            watcher.Enabled = true;

            for (int i = 0; i < 5; i++)
            {
                // Wait for events to occur. 
                System.Threading.Thread.Sleep(1000);
            }
        }
        catch (EventLogReadingException e)
        {
            Console.WriteLine("Error reading the log: {0}", e.Message);
        }
        finally
        {
            // Stop listening to events
            watcher.Enabled = false;

            if (watcher != null)
            {
                watcher.Dispose();
            }
        }
    }

    /// <summary>
    /// Callback method that gets executed when an event is
    /// reported to the subscription.
    /// </summary>
    public static void EventLogEventRead(object obj,
        EventRecordWrittenEventArgs arg)
    {
        // Make sure there was no error reading the event.
        if (arg.EventRecord != null)
        {
            Console.WriteLine("Received event {0} from the subscription.",
               arg.EventRecord.Id);
            Console.WriteLine("Description: {0}", arg.EventRecord.FormatDescription());
        }
        else
        {
            Console.WriteLine("The event instance was null.");
        }
    }
}

Compiling the Code

This code example requires references to the System.dll and System.Core.dll files.

See Also

Concepts

Event Log Scenarios
How to: Access and Read Event Information

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.