Export (0) Print
Expand All

How to: Query for Events

.NET Framework 3.5

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

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

Send comments about this topic to Microsoft.

Copyright © 2007 by Microsoft Corporation. All rights reserved.

Community Additions

Show:
© 2014 Microsoft