如何:查询事件

可以查询符合指定查询条件的一组事件,以便筛选存储在事件日志中的事件。该查询根据事件属性筛选事件。例如,可以在某个事件日志中查询在特定时间段内发生的所有级别为 2 的事件,也可以查询所有标识符等于 105 的事件。

示例

说明

下面的代码示例使用 System.Diagnostics.Eventing.Reader 类,从应用程序事件日志中查询所有级别为 2 的事件。显示查询返回的每个事件的说明、事件 ID 和事件发布程序名称。此代码示例说明如何从存档事件日志、外部事件日志及远程计算机中查询事件。此代码示例中的每个方法都执行一系列查询事件的步骤。

  1. 通过指定用于筛选事件的查询字符串和要查询的事件日志的名称或位置,创建 EventLogQuery 类的实例。若要查询外部事件日志,请指定该日志文件(扩展名为 .evtx)的路径。有关如何查找事件日志名称的详细信息,请参阅如何:配置和读取事件日志属性中的代码示例或在事件查看器工具中搜索事件日志。有关如何创建事件查询字符串的详细信息,请参阅事件查询和事件 XML

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

  3. 创建 EventLogReader 类的实例,方法是指定步骤 1 中创建的 EventLogQuery 实例。

  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 发送对本主题的评论。

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