次の方法で共有


方法 :イベント ログのイベントをサブスクライブする

特定のイベントがイベント ログに発行されたときにアプリケーションに通知するよう、イベント ログのイベントをサブスクライブできます。これによって、イベント ログを監視してタスクを実行したり、イベントが発生した時点で通知を送信したりできます。イベント通知を受信するようサブスクライブする場合は、指定したクエリ条件に一致したイベントのグループを対象とする、XPath ベースのクエリを指定します。クエリは、イベント プロパティに基づいてイベントをフィルタ処理します。たとえば、あるイベント ログのレベル 2 のイベントをすべてサブスクライブしたり、105 に一致する識別子を持つイベントをすべてサブスクライブしたりできます。

説明

次のコード例では、System.Diagnostics.Eventing.Reader クラスを使用して、アプリケーション イベント ログに記録されたレベル 2 のイベントすべてについて、イベント通知を受信するようサブスクライブします。この条件に一致したイベントがイベント ログに発行されると、その説明とイベント ID がそのイベントに表示されます。サブスクライブ対象のイベントのクエリを作成するには、EventLogQuery クラスが使用されます。次に、EventLogWatcher クラスを使用して、サブスクリプションを作成します。そのために、EventRecordWritten イベントのイベント ハンドラ メソッドを設定します。クエリ条件に一致するイベントがログに発行されると、このイベント ハンドラ メソッドが呼び出されます。

次のコード例では、イベントをサブスクライブする一連の手順に従います。

  1. イベントのフィルタ処理に使用するクエリ文字列、およびサブスクライブ対象のイベント ログの名前または場所を指定して、EventLogQuery クラスのインスタンスを作成します。イベント ログ名の検索方法の詳細については、「方法 :イベント ログのプロパティを構成し、読み取る」を参照してください。または、イベント ビューア ツールでイベント ログを検索してください。イベント クエリ文字列を作成する方法の詳細については、「イベント クエリとイベント XML」を参照してください。

  2. (オプション) リモート コンピュータのイベントをサブスクライブするには、Session プロパティを EventLogSession クラスのインスタンスに設定します。次に、リモート コンピュータに接続するために使用するリモート コンピュータ名、ドメイン、およびユーザー名とパスワードを指定します。

  3. 手順 1. で作成した EventLogQuery インスタンスを EventLogWatcher コンストラクタに渡して、EventLogWatcher インスタンスを新規作成します。

  4. イベントがサブスクリプションに報告された時点で実行されるコールバック メソッドを作成します。このメソッドは、Object 型および EventRecordWrittenEventArgs 型の引数を受け入れる必要があります。

  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 に送信する。

Copyright © 2007 by Microsoft Corporation.All rights reserved.