简体   繁体   English

订阅 Windows 事件日志?

[英]Subscription to Windows Event Log?

I'm working on a project that needs to check the Windows Event Log frequently for certain events.我正在处理一个需要经常检查某些事件的 Windows 事件日志的项目。 I'm wondering - is there a way to create a subscription to the Windows Event Log for certain events?我想知道 - 有没有办法为某些事件创建对 Windows 事件日志的订阅?

So, when the event happens (eg event id = 00001), I can get a notification in the code?那么,当事件发生时(例如事件 id = 00001),我可以在代码中收到通知吗?

If this cannot be done, then I will have to keep searching the event log, which is not efficient.如果这不能完成,那么我将不得不继续搜索事件日志,这效率不高。

As you're using C#, I think you should use Windows API to subscribe to certain Windows events.当您使用 C# 时,我认为您应该使用 Windows API 来订阅某些 Windows 事件。 You can do it by using either EventLogWatcher or EventLog class.您可以使用 EventLogWatcher 或 EventLog 类来实现。 You can find an example of creating a Windows Event Log subscription using EventLog on MSDN .您可以在MSDN上找到使用 EventLog 创建 Windows 事件日志订阅的示例。

If you prefer EventLogWatcher, refer to its limited documentation .如果您更喜欢 EventLogWatcher,请参阅其有限文档 And here is my example:这是我的例子:

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<EventRecordWrittenEventArgs>(
                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<String> xPathEnum = xPathRefs;
        // Create the property selection context using the XPath reference
        EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);

        IList<object> 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.");
    }
}

Here is a simplified example, which uses the query generated in the XML tab on the filter view of the Windows Event Viewer.这是一个简化的示例,它使用在 Windows 事件查看器的筛选器视图上的XML选项卡中生成的查询。 It loads the initial records returned by the query, then keeps watch for any future items.它加载查询返回的初始记录,然后监视任何未来的项目。

        var query = $"*[System[(EventID=1942) and TimeCreated[timediff(@SystemTime) &lt;= 604800000]]]";
        var decoded = System.Web.HttpUtility.HtmlDecode(query);
        var eventLogQuery = new EventLogQuery("Application", PathType.LogName, decoded);
        var watcher = new EventLogWatcher(eventLogQuery, null, true);
        var count = 0;

        watcher.EventRecordWritten += (object sender, EventRecordWrittenEventArgs e) =>
        {
            count += 1;

            Console.WriteLine($"Found {count} items for query");
        };

        watcher.Enabled = true;

        for (var i = 0; i < 5; i++)
        { 
            System.Threading.Thread.Sleep(10000);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM