订阅Windows事件日志?

我正在开发一个项目,需要经常检查某些事件的Windows事件日志。 我在想:

Is there a way to create a subscription of the Windows Event Log for certain event? 

那么,当事件发生时(即事件id = 00001),我可以尽快在代码中获得通知? 我正在使用c#。 如果无法做到这一点,那么我将不得不继续搜索效率不高的事件日志。

谢谢

当您使用C#时,我认为您应该使用Windows API订阅某些Windows事件。 您可以使用EventLogWatcher或EventLog类来完成。 您可以在MSDN上找到使用EventLog创建Windows事件日志订阅的示例。

如果您更喜欢EventLogWatcher,请参阅其有限的文档 。 这是我的例子:

 public static void subscribe() { EventLogWatcher watcher = null; try { EventLogQuery subscriptionQuery = new EventLogQuery( "Security", PathType.LogName, "*[System/EventID=4624]"); watcher = new EventLogWatcher(subscriptionQuery); // Make the watcher listen to the EventRecordWritten // events. When this event happens, the callback method // (EventLogEventRead) is called. watcher.EventRecordWritten += new EventHandler( EventLogEventRead); // Activate the subscription watcher.Enabled = true; for (int i = 0; i < 5; i++) { // Wait for events to occur. System.Threading.Thread.Sleep(10000); } } catch (EventLogReadingException e) { Log("Error reading the log: {0}", e.Message); } finally { // Stop listening to events watcher.Enabled = false; if (watcher != null) { watcher.Dispose(); } } Console.ReadKey(); } // Callback method that gets executed when an event is // reported to the subscription. public static void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg) { // Make sure there was no error reading the event. if (arg.EventRecord != null) { ////// // 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[9]; xPathRefs[0] = "Event/System/TimeCreated/@SystemTime"; xPathRefs[1] = "Event/System/Computer"; xPathRefs[2] = "Event/EventData/Data[@Name=\"TargetUserName\"]"; xPathRefs[3] = "Event/EventData/Data[@Name=\"TargetDomainName\"]"; // Place those strings in an IEnumberable object IEnumerable xPathEnum = xPathRefs; // Create the property selection context using the XPath reference EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum); IList logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext); Log("Time: ", logEventProps[0]); Log("Computer: ", logEventProps[1]); Log("TargetUserName: ", logEventProps[2]); Log("TargetDomainName: ", logEventProps[3]); Log("---------------------------------------"); Log("Description: ", arg.EventRecord.FormatDescription()); } else { Log("The event instance was null."); } }