다음을 통해 공유


방법: 이벤트 쿼리

지정한 쿼리 조건을 충족하는 이벤트 그룹을 쿼리하여 이벤트 로그에 저장된 이벤트를 필터링할 수 있습니다. 이 쿼리는 이벤트 속성을 기반으로 이벤트를 필터링합니다. 예를 들어, 특정 기간 내에 발생한 특정 이벤트 로그의 모든 수준 2 이벤트를 쿼리하거나 식별자가 105인 모든 이벤트를 쿼리할 수 있습니다.

예제

설명

다음 코드 예제에서는 System.Diagnostics.Eventing.Reader 클래스를 사용하여 응용 프로그램 이벤트 로그의 모든 수준 2 이벤트를 쿼리합니다. 쿼리에서 반환된 각 이벤트에 대해 설명, 이벤트 ID 및 이벤트 게시자 이름이 표시됩니다. 이 코드 예제에서는 활성 이벤트 로그, 외부 이벤트 로그 및 원격 컴퓨터의 이벤트를 쿼리하는 방법을 보여 줍니다. 이 코드 예제의 각 메서드는 일련의 단계에 따라 이벤트를 쿼리합니다.

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

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

  3. 1단계에서 만든 EventLogQuery 인스턴스를 지정하여 EventLogReader 클래스의 인스턴스를 만듭니다.

  4. 쿼리 결과를 가져오려면 ReadEvent 메서드에서 반환된 EventRecord 인스턴스를 사용합니다. 반환된 각 인스턴스는 쿼리 결과의 이벤트에 대한 이벤트 정보를 포함합니다. 이벤트 인스턴스의 이벤트 정보 읽기에 대한 자세한 내용은 방법: 이벤트 정보 액세스 및 읽기를 참조하십시오.

코드

Imports System
Imports System.Diagnostics.Eventing.Reader
Imports System.Security

Public Class EventQueryExample

    Public Overloads Shared Function Main( _
        ByVal args() As String) As Integer

        Dim ex As New EventQueryExample()
        ex.QueryActiveLog()
        ex.QueryExternalFile()
        ex.QueryRemoteComputer()
    End Function

    Public Sub QueryActiveLog()

        Dim queryString As String = "*[System/Level=2]"  ' XPATH Query
        Dim eventsQuery As New EventLogQuery("Application", PathType.LogName, queryString)
        Dim logReader As New EventLogReader(eventsQuery)

        Dim eventInstance As EventRecord = logReader.ReadEvent()
        While Not eventInstance Is Nothing
            ' Display event info
            Console.WriteLine("-----------------------------------------------------")
            Console.WriteLine("Event ID: {0}", eventInstance.Id)
            Console.WriteLine("Publisher: {0}", eventInstance.ProviderName)
            Console.WriteLine("Description: {0}", eventInstance.FormatDescription())

            eventInstance = logReader.ReadEvent()
        End While

    End Sub

    Public Sub QueryExternalFile()

        Dim queryString As String = "*[System/Level=2]" ' XPATH Query
        Dim eventLogLocation As String = "C:\MyEvents.evtx"
        Dim eventsQuery As New EventLogQuery(eventLogLocation, PathType.FilePath, queryString)

        Try
            Dim logReader As New EventLogReader(eventsQuery)

            Dim eventInstance As EventRecord = logReader.ReadEvent()
            While Not eventInstance Is Nothing
                ' Display event info
                Console.WriteLine("-----------------------------------------------------")
                Console.WriteLine("Event ID: {0}", eventInstance.Id)
                Console.WriteLine("Publisher: {0}", eventInstance.ProviderName)
                Console.WriteLine("Description: {0}", eventInstance.FormatDescription())
                eventInstance = logReader.ReadEvent()
            End While

        Catch e As EventLogNotFoundException
            Console.WriteLine("Could not find the external log to query! " & e.Message)
            Return
        End Try
    End Sub


    Public Sub QueryRemoteComputer()

        Dim queryString As String = "*[System/Level=2]"  ' XPATH Query
        Dim pw As SecureString = GetPassword()

        Dim session As EventLogSession = New EventLogSession( _
            "RemoteComputerName", _
            "Domain", _
            "Username", _
            pw, _
            SessionAuthentication.Default)

        pw.Dispose()

        ' Query the Application log on the remote computer.
        Dim query As EventLogQuery = New EventLogQuery( _
            "Application", PathType.LogName, queryString)
        query.Session = session

        Try

            Dim reader As New EventLogReader(query)
            Dim instance As EventRecord = reader.ReadEvent()
            While Not instance Is Nothing
                Console.WriteLine("------------------------------")
                Console.WriteLine("Event ID: {0}", instance.Id)
                Console.WriteLine("Description: {0}", instance.FormatDescription())
                instance = reader.ReadEvent()
            End While

        Catch e As EventLogException

            Console.WriteLine("Could not query the remote computer! " & e.Message)
            Return
        End Try
    End Sub

    ' <summary>
    ' Read a password from the console into a SecureString
    ' </summary>
    ' <returns>Password stored in a secure string</returns>
    Public Function GetPassword() As SecureString

        Dim password As New SecureString()
        Console.WriteLine("Enter password: ")

        ' get the first character of the password
        Dim nextKey As ConsoleKeyInfo = Console.ReadKey(True)

        While nextKey.Key <> ConsoleKey.Enter

            If nextKey.Key = ConsoleKey.Backspace Then
                If password.Length > 0 Then

                    password.RemoveAt(password.Length - 1)

                    ' erase the last * as well
                    Console.Write(nextKey.KeyChar)
                    Console.Write(" ")
                    Console.Write(nextKey.KeyChar)
                End If

            Else
                password.AppendChar(nextKey.KeyChar)
                Console.Write("*")
            End If

            nextKey = Console.ReadKey(True)
        End While

        Console.WriteLine()

        ' lock the password down
        password.MakeReadOnly()
        Return password

    End Function
End Class
using System;
using System.Diagnostics.Eventing.Reader;
using System.Security;

namespace EventQuery
{
    class EventQueryExample
    {
        static void Main(string[] args)
        {
            EventQueryExample ex = new EventQueryExample();
            ex.QueryActiveLog();
            ex.QueryExternalFile();
            ex.QueryRemoteComputer();
        }

        public void QueryActiveLog()
        {
            string queryString = "*[System/Level=2]";  // XPATH Query
            EventLogQuery eventsQuery = new EventLogQuery("Application", PathType.LogName, queryString);
            EventLogReader logReader = new EventLogReader(eventsQuery);

            for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                // Display event info
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine("Event ID: {0}", eventInstance.Id);
                Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
            }
        }

        public void QueryExternalFile()
        {
            string queryString = "*[System/Level=2]"; // XPATH Query
            string eventLogLocation = @"C:\MyEvents.evtx";
            EventLogQuery eventsQuery = new EventLogQuery(eventLogLocation, PathType.FilePath, queryString);

            try
            {
                EventLogReader logReader = new EventLogReader(eventsQuery);

                for (EventRecord eventInstance = logReader.ReadEvent();
                    null != eventInstance; eventInstance = logReader.ReadEvent())
                {
                    // Display event info
                    Console.WriteLine("-----------------------------------------------------");
                    Console.WriteLine("Event ID: {0}", eventInstance.Id);
                    Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                    Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                }
            }
            catch (EventLogNotFoundException e)
            {
                Console.WriteLine("Could not find the external log to query! " + e.Message);
                return;
            }
        }

        public void QueryRemoteComputer()
        {
            string queryString = "*[System/Level=2]"; // XPATH Query
            SecureString pw = GetPassword();

            EventLogSession session = new EventLogSession(
                "RemoteComputerName",                               // Remote Computer
                "Domain",                                  // Domain
                "Username",                                // Username
                pw,
                SessionAuthentication.Default);

            pw.Dispose();

            // Query the Application log on the remote computer.
            EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
            query.Session = session;

            try
            {
                EventLogReader reader = new EventLogReader(query);
                for (EventRecord instance = reader.ReadEvent(); instance != null; instance = reader.ReadEvent())
                {
                    Console.WriteLine("------------------------------");
                    Console.WriteLine("Event ID: {0}", instance.Id);
                    Console.WriteLine("Description: {0}", instance.FormatDescription());
                }
            }
            catch (EventLogException e)
            {
                Console.WriteLine("Could not query the remote computer! " + e.Message);
                return;
            }
        }

        /// <summary>
        /// Read a password from the console into a SecureString
        /// </summary>
        /// <returns>Password stored in a secure string</returns>
        public static SecureString GetPassword()
        {
            SecureString password = new SecureString();
            Console.WriteLine("Enter password: ");

            // get the first character of the password
            ConsoleKeyInfo nextKey = Console.ReadKey(true);

            while (nextKey.Key != ConsoleKey.Enter)
            {
                if (nextKey.Key == ConsoleKey.Backspace)
                {
                    if (password.Length > 0)
                    {
                        password.RemoveAt(password.Length - 1);

                        // erase the last * as well
                        Console.Write(nextKey.KeyChar);
                        Console.Write(" ");
                        Console.Write(nextKey.KeyChar);
                    }
                }
                else
                {
                    password.AppendChar(nextKey.KeyChar);
                    Console.Write("*");
                }

                nextKey = Console.ReadKey(true);
            }

            Console.WriteLine();

            // lock the password down
            password.MakeReadOnly();
            return password;
        }
    }
}

코드 컴파일

이 코드 예제에는 System.dll, System.Security.dll 및 System.Core.dll 파일에 대한 참조가 필요합니다.

참고 항목

개념

이벤트 로그 시나리오
방법: 이벤트 로그의 이벤트 알림 신청

Footer image

이 항목에 대한 의견을 Microsoft에 보내 주십시오.

Copyright © 2007 by Microsoft Corporation. All rights reserved.