Cómo consultar eventos

Puede consultar un grupo de eventos que coincida con un criterio de búsqueda especificado para filtrar los eventos almacenados en un registro de eventos. La consulta filtra los eventos basándose en las propiedades de eventos. Por ejemplo, puede consultar todos los eventos de nivel 2 de un determinado registro de eventos que haya tenido lugar en un determinado período de tiempo o consultar todos los eventos con un identificador igual a 105.

Ejemplo

Descripción

En el siguiente ejemplo de código se utilizan las clases System.Diagnostics.Eventing.Reader para consultar todos los eventos de nivel 2 del registro de eventos de la aplicación. Se muestra la descripción, el Id. de evento y el nombre del editor de eventos de todos los eventos devueltos por la consulta. En el ejemplo de código se muestra cómo consultar eventos desde un registro de eventos activo, un registro de eventos externo y desde un equipo remoto. Cada método del código de ejemplo sigue una serie de pasos para consultar los eventos.

  1. Cree una instancia de la clase EventLogQuery especificando una cadena de consulta usada para filtrar eventos y el nombre o ubicación del registro de eventos que se va a consultar. Para consultar un registro de eventos externo, especifique la ruta de acceso al archivo de registro (.evtx). Para obtener más información sobre cómo buscar nombres de registros de eventos, vea el ejemplo de código de Cómo configurar y leer propiedades del registro de eventos o busque registros de eventos en la herramienta Visor de eventos. Para obtener más información sobre cómo crear una cadena de consulta de eventos, vea Consultas de eventos y XML de eventos.

  2. (Opcional) Para consultar eventos desde un equipo remoto, establezca la propiedad Session en una instancia de la clase EventLogSession y especifique el nombre del equipo remoto, el dominio y el nombre de usuario y la contraseña usados para conectarse al equipo remoto.

  3. Cree una instancia de la clase EventLogReader especificando la instancia EventLogQuery que se ha creado en el paso 1.

  4. Para obtener los resultados de la consulta, use las instancias de EventRecord devueltas en el método ReadEvent. Cada instancia devuelta almacena información de evento para un evento del resultado de búsqueda. Para obtener más información sobre cómo leer la información de eventos en una instancia de eventos, vea Cómo tener acceso y leer información de eventos.

Código

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

Compilar el código

Este ejemplo de código requiere referencias a los archivos System.dll, System.Security.dll y System.Core.dll.

Consulte también

Conceptos

Escenarios de registros de eventos
Cómo suscribirse a eventos de un registro de eventos

Footer image

Enviar comentarios sobre este tema a Microsoft.

Copyright © 2007 Microsoft Corporation. Reservados todos los derechos.