다음을 통해 공유


방법: 이벤트 로그의 이벤트 알림 신청

특정 이벤트가 이벤트 로그에 게시될 때 응용 프로그램에 알림이 제공되도록 이벤트 로그의 이벤트에 대해 알림을 신청할 수 있습니다. 이를 통해 이벤트 로그를 모니터링하고 이벤트 발생 시 작업을 수행하거나 알림을 보낼 수 있습니다. 이벤트 알림을 받도록 신청할 때 지정한 쿼리 조건에 충족하는 이벤트 그룹에 대한 XPath 기반 쿼리를 지정합니다. 이 쿼리는 이벤트 속성을 기반으로 이벤트를 필터링합니다. 예를 들어, 특정 이벤트 로그의 모든 수준 2 이벤트에 대해 알림을 신청하거나 식별자가 105인 모든 이벤트에 대해 알림을 신청할 수 있습니다.

예제

설명

다음 코드 예제에서는 System.Diagnostics.Eventing.Reader 클래스를 사용하여 응용 프로그램 이벤트 로그의 모든 수준 2 이벤트에 대한 이벤트 알림을 받습니다. 이 조건을 충족하는 이벤트가 이벤트 로그에 게시되면 이벤트에 대해 설명 및 이벤트 ID가 표시됩니다. EventLogQuery 클래스를 사용하여 알림을 신청할 이벤트에 대한 쿼리를 만듭니다. 그런 다음 EventLogWatcher 클래스를 통해 EventRecordWritten 이벤트에 대한 이벤트 처리기 메서드를 설정하여 알림 신청을 만듭니다. 쿼리 조건을 충족하는 이벤트가 로그에 게시되면 이벤트 처리기 메서드가 호출됩니다.

다음 코드 예제에서는 이벤트 알림을 신청하는 일련의 단계를 진행합니다.

  1. 이벤트 필터링에 사용되는 쿼리 문자열과 알림을 신청할 이벤트 로그의 이름이나 위치를 지정하여 EventLogQuery 클래스의 인스턴스를 만듭니다. 이벤트 로그 이름을 찾는 방법에 대한 자세한 내용은 방법: 이벤트 로그 속성 구성 및 읽기를 참조하거나 이벤트 뷰어 도구에서 이벤트 로그를 검색하십시오. 이벤트 쿼리 문자열을 만드는 방법에 대한 자세한 내용은 이벤트 쿼리 및 이벤트 XML를 참조하십시오.

  2. (옵션) 원격 컴퓨터의 이벤트에 대해 알림을 신청하려면 Session 속성을 EventLogSession 클래스의 인스턴스로 설정하고 원격 컴퓨터 이름, 도메인 및 원격 컴퓨터에 연결하는 데 사용되는 사용자 이름과 암호를 지정합니다.

  3. 1단계에서 만든 EventLogQuery 인스턴스를 EventLogWatcher 생성자에 전달하여 새 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에 보내 주십시오.

Copyright © 2007 by Microsoft Corporation. All rights reserved.