Read Event Log From Newest to Oldest

a 夏天 提交于 2019-12-30 07:04:13

问题


I have written a short program to establish the uptime for remote PC's using the event log messages which are posted at startup and shutdown. Currently the logic is :

  foreach (eventlogentry)
  {
       if (entryTime > OldestTime)
       {
            if (entry = Startup)
            {
                 addOnTime(entry.Time);
            }
            if (entry = Shutdown)
            {
                 addOffTime(entry.Time);
            }
       }
  }

"OldestTime" define how far to scan backwards in time....

I would like to know if there is anyway to easily ammend my program to read the events from newest to oldest?

It's reading remote event logs and its taking a while for this function to run, as it starts at the end and reads forward.

I know this because I added a "else" block to the first "if" to break out of the foreach block, if the entry isnt within the timespan we are looking for and the program stop's at the first event it reads.


回答1:


It has been a while since you asked this question, but i ran into the same problem and found a solution.

using System.Diagnostics;
using System.Linq;

EventLog events = new EventLog("Application", System.Environment.MachineName);
foreach (EventLogEntry entry in  events.Entries.Cast<EventLogEntry>().Reverse())
{
    //Do your tasks
}

This awnser still is not as fast as to just enumerate it forward but it is a bit more elegant than using a loop to copy items to a list.

@leinad13, for your application you need to change System.Environment.MachineName to a string with the name of the computer you want the events from and change "Application" to the log you want to see. I think "System" in your case.




回答2:


Your best solution may be to move the data into a list and then reverse the order of that. Something like the following:

EventLog eventLog = new EventLog();
eventLog.Log = myEventLog;
var eventList = new List<EventLogEntry>();

foreach(EventLogEntry entry in eventLog.Entries)
{
      eventList.Add(entry);
}

eventList.Reverse();

That should get the data in the reverse order, i.e. latest first, and then you can just process it as before but this time exit the loop when you hit a date before the oldest time.

Its not an ideal solution as you are still processing the whole log but it may be worth trying out to see if you get an improvement in performance



来源:https://stackoverflow.com/questions/7023472/read-event-log-from-newest-to-oldest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!