Sdílet prostřednictvím


How to: Query for Events

You can query for a group of events that match a specified query criteria to filter the events stored in an event log. The query filters events based on event properties. For example, you can query for all level 2 events in a certain event log that occurred in a certain time period, or you can query for all the events with an identifier equal to 105.

Example

Description

The following code example uses the System.Diagnostics.Eventing.Reader classes to query for all the level 2 events from the Application event log. The description, event ID, and the event publisher name are displayed for each event returned from the query. The code example shows how to query for events from an active event log, an external event log, and from a remote computer. Each method in this code example follows a series of steps to query for events.

  1. Create an instance of the EventLogQuery class by specifying a query string used to filter events, and the name or location of the event log to query. To query an external event log, specify the path to the log file (.evtx). For more information about how to find event log names, see the code example in How to: Configure and Read Event Log Properties or search for event logs in the Event Viewer tool. For more information about how to create an event query string, see Event Queries and Event XML.

  2. (Optional) To query for events from a remote computer, set the Session property to an instance of the EventLogSession class and specify the remote computer name, domain, and the user name and password used to connect to the remote computer.

  3. Create an instance of the EventLogReader class by specifying the EventLogQuery instance that was created in Step 1.

  4. To get the query results, use the EventRecord instances returned from the ReadEvent method. Each returned instance holds event information for an event in the query results. For more information about reading the event information from an event instance, see How to: Access and Read Event Information.

Code

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()

        ' Query two different event logs using a structured query.
        Dim queryString As String = _
                "<QueryList>" & _
                "  <Query Id=""0"" Path=""Application"">" & _
                "    <Select Path=""Application"">" & _
                "        *[System[(Level &lt;= 3) and" & _
                "        TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]" & _
                "    </Select>" & _
                "    <Suppress Path=""Application"">" & _
                "        *[System[(Level = 2)]]" & _
                "    </Suppress>" & _
                "    <Select Path=""System"">" & _
                "        *[System[(Level=1  or Level=2 or Level=3) and" & _
                "        TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]" & _
                "    </Select>" & _
                "  </Query>" & _
                "</QueryList>"

        Dim eventsQuery As New EventLogQuery("Application", PathType.LogName, queryString)
        Dim logReader As New EventLogReader(eventsQuery)

        ' Display query results.
        DisplayEventAndLogInformation(logReader)

    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)

            ' Display query results.
            DisplayEventAndLogInformation(logReader)

        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 logReader As New EventLogReader(query)

            ' Display query results.
            DisplayEventAndLogInformation(logReader)

        Catch e As EventLogException

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


    ' Displays the event query results (the event information and log
    ' information for all the events returned from the query).
    Private Sub DisplayEventAndLogInformation(ByVal logReader As EventLogReader)

        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)


            Try
                Console.WriteLine("Description: {0}", eventInstance.FormatDescription())

            Catch e As EventLogException

                ' The event description contains parameters, and no parameters were 
                ' passed to the FormatDescription method, so an exception is thrown.

            End Try

            eventInstance = logReader.ReadEvent()

            ' Cast the EventRecord object as an EventLogRecord object to 
            ' access the EventLogRecord class properties.
            Dim logRecord As EventLogRecord = CType(eventInstance, EventLogRecord)
            Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog)
        End While

    End Sub


    ' Read a password from the console into a SecureString
    ' <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()
        {
            // Query two different event logs using a structured query.
            string queryString =
                "<QueryList>" +
                "  <Query Id=\"0\" Path=\"Application\">" +
                "    <Select Path=\"Application\">" +
                "        *[System[(Level &lt;= 3) and" +
                "        TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]" +
                "    </Select>" +
                "    <Suppress Path=\"Application\">" +
                "        *[System[(Level = 2)]]" +
                "    </Suppress>" +
                "    <Select Path=\"System\">" +
                "        *[System[(Level=1  or Level=2 or Level=3) and" +
                "        TimeCreated[timediff(@SystemTime) &lt;= 86400000]]]" +
                "    </Select>" +
                "  </Query>" +
                "</QueryList>"; 

            EventLogQuery eventsQuery = new EventLogQuery("Application", PathType.LogName, queryString);
            EventLogReader logReader = new EventLogReader(eventsQuery);

            // Display event info
            DisplayEventAndLogInformation(logReader);

        }

        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);

                // Display event info
                DisplayEventAndLogInformation(logReader);
            }
            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 logReader = new EventLogReader(query);

                // Display event info
                DisplayEventAndLogInformation(logReader);
            }
            catch (EventLogException e)
            {
                Console.WriteLine("Could not query the remote computer! " + e.Message);
                return;
            }
        }

        /// <summary>
        /// Displays the event information and log information on the console for 
        /// all the events returned from a query.
        /// </summary>
        private void DisplayEventAndLogInformation(EventLogReader logReader)
        {
            for (EventRecord eventInstance = logReader.ReadEvent();
                null != eventInstance; eventInstance = logReader.ReadEvent())
            {
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine("Event ID: {0}", eventInstance.Id);
                Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
                
                try
                {
                    Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
                }
                catch (EventLogException)
                {
                    // The event description contains parameters, and no parameters were 
                    // passed to the FormatDescription method, so an exception is thrown.

                }

                // Cast the EventRecord object as an EventLogRecord object to 
                // access the EventLogRecord class properties
                EventLogRecord logRecord = (EventLogRecord)eventInstance;
                Console.WriteLine("Container Event Log: {0}", logRecord.ContainerLog);
            }
        }

        /// <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;
        }
    }
}

Compiling the Code

This code example requires references to the System.dll, System.Security.dll, and System.Core.dll files.

See Also

Concepts

Event Log Scenarios
How to: Subscribe to Events in an Event Log

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.