Freigeben über


Verfahrensweise: Zugreifen auf und Lesen von Ereignisinformationen

Beim Abrufen einer Ereignisinstanz aus einer Ereignisabfrage oder einem Ereignisabonnement können die Werte der Ereigniseigenschaften gelesen werden. Hierzu rufen Sie die XML-Darstellung des Ereignisses ab, oder Sie geben den Namen der zu lesenden Eigenschaft an.

Weitere Informationen zum Abfragen von Ereignissen finden Sie unter Verfahrensweise: Abfragen von Ereignissen. Weitere Informationen zum Abonnieren von Ereignissen finden Sie unter Verfahrensweise: Abonnieren von Ereignissen in einem Ereignisprotokoll.

Beispiel

Beschreibung

Im folgenden Codebeispiel werden alle im Anwendungsprotokoll vorkommenden Ereignisse der 2. Stufe abgefragt. Danach wird von jedem Ereignis die XML-Darstellung angezeigt. Jede von der Ereignisabfrage zurückgegebene Ereignisinstanz wird von einer EventRecord-Instanz dargestellt. Die ToXml-Methode wird aufgerufen, um die XML-Darstellung des Ereignisses abzurufen.

Imports System
Imports System.Text
Imports System.Diagnostics.Eventing.Reader
Imports System.Xml

Public Class ReadEventXmlExample

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

        Dim logName As String = "Application"
        Dim queryString As String = "*[System/Level=2]"

        Dim eventsQuery As New EventLogQuery(logName, _
            PathType.LogName, queryString)

        Dim logReader As EventLogReader
        Console.WriteLine("Querying the Application channel event log for all events...")
        Try

            ' Query the log and create a stream of selected events
            logReader = New EventLogReader(eventsQuery)

        Catch e As EventLogNotFoundException

            Console.WriteLine("Failed to query the log!")
            Console.WriteLine(e)
            Return 1
        End Try

        Dim numberOfEvents As Integer = 0

        ' For each event returned from the query
        Dim eventInstance As EventRecord = logReader.ReadEvent()
        While Not eventInstance Is Nothing

            Dim eventXml As String = eventInstance.ToXml()
            Console.WriteLine("Event " & (++numberOfEvents) & " : " & _
                System.Environment.NewLine & eventXml)
            Console.WriteLine("---------------------------------")
            eventInstance = logReader.ReadEvent()
        End While

    End Function
End Class
using System;
using System.Text;
using System.Diagnostics.Eventing.Reader;
using System.Xml;

class ReadEventXmlExample
{
    static void Main(string[] args)
    {
        String logName = "Application";
        String queryString = "*[System/Level=2]";

        EventLogQuery eventsQuery = new EventLogQuery(logName,
            PathType.LogName, queryString);

        EventLogReader logReader;
        Console.WriteLine("Querying the Application channel event log for all events...");
        try
        {
            // Query the log and create a stream of selected events
            logReader = new EventLogReader(eventsQuery);
        }
        catch (EventLogNotFoundException e)
        {
            Console.WriteLine("Failed to query the log!");
            Console.WriteLine(e);
            return;
        }

        int numberOfEvents = 0;
        // For each event returned from the query
        for (EventRecord eventInstance = logReader.ReadEvent();
                eventInstance != null;
                eventInstance = logReader.ReadEvent())
        {
            String eventXml = eventInstance.ToXml();
            Console.WriteLine("Event " + (++numberOfEvents) + " : " + System.Environment.NewLine + eventXml);
            Console.WriteLine("---------------------------------");
            //Console.ReadLine();
        }
    }
}

Kompilieren des Codes

Für dieses Codebeispiel werden Verweise auf die Dateien System.dll und System.Core.dll benötigt.

Beispiel

Beschreibung

Im folgenden Codebeispiel wird mithilfe der EventLogPropertySelector-Klasse eine Ereignisinstanz als Liste angegebener Werte gerendert. Die angegebenen Werte bestehen aus dem das Ereignis protokollierenden Benutzer, der Uhrzeit der Erzeugung des Ereignisses, dem Ereignisbezeichner und dem Ereignisdatensatzbezeichner.

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Diagnostics.Eventing.Reader

Public Class ReadEventValuesExample

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

        Dim logName As String = "Application"
        Dim queryString As String = "*[System/Level=2]"

        Dim eventsQuery As New EventLogQuery(logName, _
            PathType.LogName, queryString)

        Dim logReader As EventLogReader
        Console.WriteLine("Querying the Application channel event log for all events...")

        Try
            ' Query the log
            logReader = New EventLogReader(eventsQuery)

        Catch e As EventLogNotFoundException

            Console.WriteLine("Failed to query the log!")
            Console.WriteLine(e)
            Return 1
        End Try

        '''''''
        ' This section creates a list of XPath reference strings to select
        ' the properties that we want to display
        ' In this example, we will extract the User, TimeCreated, EventID and EventRecordID
        '''''''
        ' Array of strings containing XPath references
        Dim xPathRefs(3) As String
        xPathRefs(0) = "Event/System/Security/@UserID"
        xPathRefs(1) = "Event/System/TimeCreated/@SystemTime"
        xPathRefs(2) = "Event/System/EventID"
        xPathRefs(3) = "Event/System/EventRecordID"

        ' Place those strings in an IEnumberable object
        Dim xPathEnum As IEnumerable(Of String) = xPathRefs
        ' Create the property selection context using the XPath reference
        Dim logPropertyContext As New EventLogPropertySelector(xPathEnum)

        Dim numberOfEvents As Integer = 0

        ' For each event returned from the query
        Dim eventInstance As EventLogRecord = logReader.ReadEvent()
        While Not eventInstance Is Nothing
            Dim logEventProps As IList(Of Object)

            Try
                ' Cast the EventRecord into an EventLogRecord to retrieve property values.
                ' This will fetch the event properties we requested through the
                ' context created by the EventLogPropertySelector
                logEventProps = eventInstance.GetPropertyValues(logPropertyContext)
                Console.WriteLine("Event {0} :", ++numberOfEvents)
                Console.WriteLine("User: {0}", logEventProps(0))
                Console.WriteLine("TimeCreated: {0}", logEventProps(1))
                Console.WriteLine("EventID: {0}", logEventProps(2))
                Console.WriteLine("EventRecordID : {0}", logEventProps(3))

                ' Event properties can also be retrived through the event instance
                Console.WriteLine("Event Description:" + eventInstance.FormatDescription())
                Console.WriteLine("MachineName: " + eventInstance.MachineName)

            Catch e As Eventing.Reader.EventLogException
                Console.WriteLine("Couldn't render event!")
                Console.WriteLine("Exception: Event {0} may not have an XML representation \n\n", ++numberOfEvents)
                Console.WriteLine(e)
            End Try

            eventInstance = logReader.ReadEvent()
        End While
    End Function
End Class
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics.Eventing.Reader;

class ReadEventValuesExample
{
    static void Main(string[] args)
    {
        String logName = "Application";
        String queryString = "*[System/Level=2]";

        EventLogQuery eventsQuery = new EventLogQuery(logName,
            PathType.LogName, queryString);

        EventLogReader logReader;
        Console.WriteLine("Querying the Application channel event log for all events...");
        try
        {
            // Query the log
            logReader = new EventLogReader(eventsQuery);
        }
        catch (EventLogNotFoundException e)
        {
            Console.WriteLine("Failed to query the log!");
            Console.WriteLine(e);
            return;
        }

        //////
        // This section creates a list of XPath reference strings to select
        // the properties that we want to display
        // In this example, we will extract the User, TimeCreated, EventID and EventRecordID
        //////
        // Array of strings containing XPath references
        String[] xPathRefs = new String[4];
        xPathRefs[0] = "Event/System/Security/@UserID";
        xPathRefs[1] = "Event/System/TimeCreated/@SystemTime";
        xPathRefs[2] = "Event/System/EventID";
        xPathRefs[3] = "Event/System/EventRecordID";
        // Place those strings in an IEnumberable object
        IEnumerable<String> xPathEnum = xPathRefs;
        // Create the property selection context using the XPath reference
        EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

        int numberOfEvents = 0;
        // For each event returned from the query
        for (EventRecord eventInstance = logReader.ReadEvent();
                eventInstance != null;
                eventInstance = logReader.ReadEvent())
        {
            IList<object> logEventProps;
            try
            {
                // Cast the EventRecord into an EventLogRecord to retrieve property values.
                // This will fetch the event properties we requested through the
                // context created by the EventLogPropertySelector
                logEventProps = ((EventLogRecord)eventInstance).GetPropertyValues(logPropertyContext);
                Console.WriteLine("Event {0} :", ++numberOfEvents);
                Console.WriteLine("User: {0}", logEventProps[0]);
                Console.WriteLine("TimeCreated: {0}", logEventProps[1]);
                Console.WriteLine("EventID: {0}", logEventProps[2]);
                Console.WriteLine("EventRecordID : {0}", logEventProps[3]);

                // Event properties can also be retrived through the event instance
                Console.WriteLine("Event Description:" + eventInstance.FormatDescription());
                Console.WriteLine("MachineName: " + eventInstance.MachineName);
            }
            catch (Exception e)
            {
                Console.WriteLine("Couldn't render event!");
                Console.WriteLine("Exception: Event {0} may not have an XML representation \n\n", ++numberOfEvents);
                Console.WriteLine(e);
            }
        }
    }
}

Kompilieren des Codes

Für dieses Beispiel werden Verweise auf die Dateien System.dll und System.Core.dll benötigt.

Siehe auch

Konzepte

Ereignisprotokollszenarien

Footer image

Senden Sie Kommentare zu diesem Thema an Microsoft.

Copyright © 2007 by Microsoft Corporation. Alle Rechte vorbehalten.