如何:订阅事件日志中的事件

可以订阅事件日志中的事件,以便在事件日志中发布特定事件时通知您的应用程序。这样可以监视事件日志并在事件发生时执行任务或发送通知。订阅接收事件通知时,应指定一个基于 XPath 的查询,用于查询符合指定查询条件的一组事件。该查询根据事件属性筛选事件。例如,可以订阅某个事件日志中所有级别为 2 的事件,或者订阅所有标识符等于 105 的事件。

示例

说明

下面的代码示例使用 System.Diagnostics.Eventing.Reader 类,针对应用程序事件日志中所有级别为 2 的事件订阅接收事件通知。事件日志中发布符合此条件的事件时,将显示该事件的说明和事件 ID。EventLogQuery 类用于针对要订阅的事件创建查询。然后可以使用 EventLogWatcher 类创建订阅,方法是为 EventRecordWritten 事件设置一个事件处理程序方法。如果符合查询条件的事件发布到日志中,则调用此事件处理程序方法。

下面的代码示例中执行了一系列订阅事件的步骤。

  1. 通过指定用于筛选事件的查询字符串和要订阅的事件日志的名称或位置,创建 EventLogQuery 类的实例。有关如何查找事件日志名称的详细信息,请参阅如何:配置和读取事件日志属性或者在事件查看器工具中搜索事件日志。有关如何创建事件查询字符串的详细信息,请参阅事件查询和事件 XML

  2. (可选)若要订阅远程计算机上的事件,请将 Session 属性设置为 EventLogSession 类的实例,并指定远程计算机名称、域以及用于连接到远程计算机的用户名和密码。

  3. 新建一个 EventLogWatcher 实例,方法是将步骤 1 中创建的 EventLogQuery 实例传递到 EventLogWatcher 构造函数。

  4. 创建一个回调方法,如果有事件报告到订阅,则执行该回调方法。此方法应该接受 ObjectEventRecordWrittenEventArgs 类型的参数。

  5. EventRecordWritten 事件处理程序设置为新的事件处理程序,该事件处理程序指向步骤 4 中创建的回调方法。

  6. Enabled 属性设置为等于 true 将启动事件订阅,设置为 false 将停止事件订阅。

代码

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.");
        }
    }
}

编译代码

此代码示例需要引用 System.dll 和 System.Core.dll 文件。

请参见

概念

事件日志方案
如何:访问和读取事件信息

Footer image

向 Microsoft 发送对本主题的评论。

版权所有 (C) 2007 Microsoft Corporation。保留所有权利。