Udostępnij za pośrednictwem


How to: Listen for Events and Store Them in a SQL Database

Administrators often monitor the Windows event log for specific applications, services, or errors. When you learn how to query the event log for certain events, that are identified by a particular query string, the challenge is to mine the event data. An event may contain critical information. Administrators typically perform notifications or create a task for corrective action, such as restarting a service or rebooting a server. For example, an administrator of a medium-sized network may need to screen the events from the event logs on many computers and create an alert when certain patterns occur. It may be useful to create an email notification based on a task success or failure. Event forwarding may be used to monitor several computers simultaneously.

The following code example shows how to manage events forwarded from many computers. In its simplest form, it can gather events and save them to an XML file. This XML file can then be programmatically queried to monitor specific conditions or patterns. The one problem that administrators commonly encounter is that the number of events grows quickly, making it more resource-intensive to search through the XML logs and mine the required information. By alternating a Boolean setting, this example shows how to write the event information to a SQL database. Writing data to a SQL database is useful because:

  • It enables the scalability of querying over event records.

  • It enables creation of alerts and email notifications using SQL notification.

  • It enables generation of activity reports using SQL reporting.

The following code example uses the System.Diagnostics.Eventing.Reader namespace classes to subscribe to the specified events. When an event, that matches the specified criteria, is published in the event log, the event data is gathered by the listener. The EventLogQuery class is used to specify the criteria that form the query for the events. The EventLogWatcher class is used to create a 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.

Example

To understand this example, it is helpful to understand the main parts:

Compiling the Code

This example requires references to the System.dll and System.Core.dll files. Additionally, it references the System.Data.dll and System.Xml.dll to manipulate the event XML and write the data to a SQL database. When running this example, ensure that you elevate status to administrator, otherwise you may not be able to access certain event log channels.

See Also

Concepts

Event Log Scenarios

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.