Export (0) Print
Expand All

How to: Subscribe to Events in an Event Log

.NET Framework 3.5

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

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

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.

Community Additions

Show:
© 2014 Microsoft