我正在开发一个读取和显示 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/