How to Query for an event log details with a given event id?

后端 未结 2 1632
梦谈多话
梦谈多话 2020-11-30 08:07
  1. How to know whether a particular event (given event ID, time and node as inputs) is logged or not? [In this case, I know only one event will be logged]
  2. If the
相关标签:
2条回答
  • 2020-11-30 08:44

    There are a few new twists if your going to query events from the new style Windows EventLogs.

    1. You will have to use the classes from the System.Diagnostics.Eventing.Reader namespace to read the new events.
    2. Your query will be in Xpath form, so that time value is tricky, see msdn for the EventLogQuery definition.
    3. Your program will run into access issues, be ready to impersonate a user that's included in the EventReaders AD group on the logging machine.

    This sample shows some of the new access methods, cheers.

    string eventID = "5312";
    string LogSource = "Microsoft-Windows-GroupPolicy/Operational";  
    string sQuery = "*[System/EventID=" + eventID + "]";
    
    var elQuery = new EventLogQuery(LogSource, PathType.LogName, sQuery);
    using (var elReader = new System.Diagnostics.Eventing.Reader.EventLogReader(elQuery))
    {
    
        List<EventRecord> eventList = new List<EventRecord>();
        EventRecord eventInstance = elReader.ReadEvent();
        try
        {
            for (null != eventInstance; eventInstance = elReader.ReadEvent())
            {
                //Access event properties here:
                //eventInstance.LogName;
                //eventInstance.ProviderName;
                eventList.Add(eventInstance);
            }
        }
        finally
        {
            if (eventInstance != null)
                eventInstance.Dispose();
        }
    }
    
    0 讨论(0)
  • 2020-11-30 08:44

    You could query the event log in question:

    var sourceName = "MySource";
    var el = new EventLog("Application");
    var latestEntryTime = (from entry in el.Entries.Cast<EventLogEntry>()
                           where entry.Source == sourceName
                           && // put other where clauses here...
                           orderby entry.TimeWritten descending
                           select entry).First();
    

    However, be warned that this approach is slow, since the Entries collection tends to be quite big.

    0 讨论(0)
提交回复
热议问题