c# - 如何只读取添加到事件日志的新事件?

标签 c# windows winapi event-log

我正在开发一个读取和显示 Windows 事件日志的项目。我使用以下代码从事件日志中读取事件并显示它们。

public static void Main(string[] args)
{
    EventLog[] ev;

    ev = EventLog.GetEventLogs();

    Console.WriteLine("Number of logs on computer: " + ev.Length);

    foreach (EventLog log in ev)
    {
        Console.WriteLine("Log: " + log.Log);
        foreach (EventLogEntry entry in log.Entries)
        {
            Console.WriteLine("Entry: " + entry.Message);
            Console.WriteLine("Source: " + entry.Source);
            Console.WriteLine("Category: " + entry.Category);
            Console.WriteLine("EventID: " + entry.Source);
        }
    }
}

这段代码工作正常。它显示已存储在日志文件中的所有事件。但在此之后我想要实现的是,我必须读取即将发生的事件并每 10 秒更新一次

如果我继续并再次调用相同的函数,我将获得所有事件,但我只想要新添加的事件。我如何实现这一点?

TL DR:我只想收听事件日志中新添加的事件,而不是整个事件日志

最佳答案

你可以这样做

EventLog appLogs = new EventLog("Application");

var entries = appLogs.Entries.Cast<EventLogEntry>()
                     .Where(x => x.TimeWritten >= DateTime.Now.AddMinutes(-60))
                     .ToList();

但是,无论您按什么时间过滤并不重要,它仍然需要相同的时间。

我不知道有什么办法可以加快速度(据我所知)

尽管您可能想查看 EventLog.EntryWritten Event

Occurs when an entry is written to an event log on the local computer.

Remnarks

To get event notifications, you must set EnableRaisingEvents to true. You can only receive event notifications when entries are written on the local computer. You cannot receive notifications for entries written on remote computers.

EventLog myNewLog = new EventLog("Application", ".", "testEventLogEvent");                 

myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten);
myNewLog.EnableRaisingEvents = true;

大概这比尝试轮询 EventLog Plumbing 更轻松

关于c# - 如何只读取添加到事件日志的新事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53954979/

相关文章:

windows - 如何在 Mac 和 Windows 上找到 iTunes 资料库文件夹?

windows - splunk 解析 IIS 日志文件

c# - 如何使用 C# 更新 powerpoint 幻灯片中的文本

c# - 运行由 ASP.NET 网页请求触发的异步操作

c# - 使用 C# 在 Skype 上错过聊天

windows - 将 Sitecore PowerShell 扩展与 native PowerShell 结合使用

c++ - 文本编辑器中的行管理

c# - C# 中用于获取 CPU ID 和驱动器/卷序列号的 API

winapi - 如果设置了鼠标 Hook ,则关闭窗口会延迟

c# - 什么是 MVVM 处理 “insertion” 的正确方法