Search code examples
c#event-log

Windows Application Log Events being 'missed' somehow with my EventLog


I've written an application, a component of which watches for Events being raised in the Windows Application Log with a certain Source and EventID in order to parse data from them. However, it appears to miss some of these events for no readily apparent reason.

I have included debug messages to try to see where the issue is - this takes the form of comments sent to a text field.

When an Entry is written to the application log, a time-stamped message is added to the debug text field, and parseApplicationLogEntry() is called.

private void eventLogApplication_EntryWritten(object sender,
                                          System.Diagnostics.EntryWrittenEventArgs e)
{
    txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() + 
        + ": Application Log has been written."; 
    parseApplicationLogEntry(); 
} 

The application log entry is parsed, and the Source and EventID are looked at to determine if they are what we are looking for. A time-stamped message is added to the debug text showing the Source and EventID found.

private void parseApplicationLogEntry()
{
    System.Diagnostics.EventLog log = new System.Diagnostics.EventLog("Application"); 
    int entry = log.Entries.Count - 1; 
    string logMessage = log.Entries[entry].Message;
    string logSource = log.Entries[entry].Source; 
    string logEventID = log.Entries[entry].InstanceId.ToString(); 
    log.Close(); 
    txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() + 
        ": Application Log Source is " + logSource;
    txtDebug.Text = txtDebug.Text + "\n " + DateTime.Now.ToLongTimeString() + 
        ": Application Log EventID is " + logEventID; 

    if (logSource == "ExpectedSource" & logEventID == "ExpectedEventID")
    {
        // Do stuff 
    } 
}

The behaviour is as expected much of the time, however sometimes there is very odd behaviour.

For example, 13 logs were written to the application log. 3 with the looked-for source, and 10 with another source. The debug text shows 13 entries were seen, all with the unfamiliar source...

I'm not sure where to go from here.


Solution

  • 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    
    }