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

No code example is currently available or this language may not be supported.

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: