Problem Context

My application needs to look at some entries in the EventLog whenever a new entry is written to the Application log, in order to check if the originated with a specific application.

To do this, I have a 'typical' event handler (private void eventLog__EntryWritten(object sender, System.Diagnostics.EventWrittenEventArgs e)) which then calls a method to parseApplicationLogEntries().

My application is looking for entries since a certain time. So, to do so -

System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application"); 

// The firstLog since the startTime defaults to the last index 
// (since an entry has just been written to the application log 
/// there must have been at least one since the start time) 
int firstLog = log.Entries.Count - 1; 

// Enter a for loop from the last entry in the log, backwards to 0 
for (int entry = log.Entries.Count - 1; entry > 0; entry --) 
{ 
    // Gets the time the log entry was written to compare to the start time
    DateTime logEntryTimeWritten = log.Entries[entry].TimeWritten; 

    // Compares the time the log entry was written with the start time
    if (logEntryTimeWritten < startTime) 
    {
        // If the time the log entry was written was *before* the start time
        // then our first log entry is the one after this, so save the 
        // index of the first log entry, then break out of the for loop
        firstLog = entry + 1; 
        break; 
    } 
}

Problem

My problem is, when the EventLog reaches a certain size (e.g. hits its maximum) then this starts causing errors. Unhandled IndexOutOfRangeException errors occur. As this index which is out of range was less than the Count of the Entries, I was confused...

Now, I have a theory as to why these are occurring. The default behavior for Application Logs is to "Overwrite events as needed" once the maximum size is reached. This makes me think they must be adding entries with new indexes and removing old entries (or something) which means some of my indexes which are > Count do not have an entry there... (Please forgive me if this a misguided theory)

Obviously I should be handling any case where an index is not found (which I will add, so it just skips over any out of range). However, if my theory is correct, how do I find the index value of the most recent entry in the event log if it is not equal to Count - 1? (If my theory is incorrect, what could be going on here?)

Thanks!

1

There are 1 answers

0
Eilidh On BEST ANSWER

There is no need to access the EventLog in this way to review the newest entries.

Instead of calling a method to iterate through the EventLog each time a new Entry is written, it is simpler (and safer) to access the Entry more directly using the event handler which triggers each time an Entry is written.

private void eventLog_Application_EntryWritten(object sender, EntryWrittenEventArgs e)
{
    // Process e.Entry    
}