I'm trying to retrieve the most recent events from an event log. I found this answer Read Event Log From Newest to Oldest but it involves loading the whole log which I wish to avoid.
So I tried going to the end of the log first likes this:
var eventLog = EventLog.GetEventLogs().OfType<EventLog>().Single(el => el.Log == "Security");
int logSize = eventLog.Entries.Count;
var lastScanTime = DateTime.Now.AddDays(-1),
for (int i = logSize - 1; i >= 0; i--)
{
var entry = eventLog.Entries[i];
if (entry.TimeWritten <= lastScanTime)
{
break;
}
entry.Dump();
}
This works for a while, but if I keep running it I start to get IndexOutOfRangeExceptions
It seems that the eventLog.Entries.Count no longer matches the number of entries, which you can check with the followiog code:
var eventLog = EventLog.GetEventLogs().OfType<EventLog>().Single(el => el.Log == "Security");
int size = eventLog.Entries.Count.Dump();
int size2 = eventLog.Entries.Cast<EventLogEntry>().ToList().Count.Dump();
The two size values return different values. Entries.Countkeeps growing but the number of entries in the list stops increasing. The count also matches what I see in the Windows Event Log viewer.
Its like something in the .net API breaks and no more events are available.
Anybody seen this before or have any fixes to get this approach to work.
Edit: I also found this A mystery IndexOutOfRange Exception recurring when reading from a full EventLog which seems like a similar problem but no solution. I can't use events because I may be looking to activity on the machine before my software is installed.
Edit: If I catch exceptions and put the results into a list I get a different number of events again:
var results = new List<EventLogEntry>();
for (int i = eventLog.Entries.Count; i >= 0; i--)
{
try
{
var entry = eventLog.Entries[i];
{
results.Add(entry);
}
}
catch (Exception ex) { }
}
It has a lower count than Entries.Count but more recent logs entries than Entries does which seems to have just stopped at a certain point.
In case anyone else has the same issue it seems to be a result of not always disposing of the EventLog object after reading from file.
Once this happens it seems to break or corrupt the file in some way any you can't get more recent data until you clear the file out.