Event Logging – Reading the Event Log

Yesterday we created some code that wrote messages to the event log, and showed how to use the Microsoft Management Console (MMC) to review those messages. For the average user though, running the MMC may be a bit out of their normal comfort bounds. Instead, we need to be able to access the log from within our application. Again, the .Net Framework makes this easy.

First you’ll need to create an EventLog object, as we did with the writing. Then set the log property to the log we write to. Finally you will need to loop through the Entries collection of the EventLog, looking at each EventLogEntry object. Here’s a quick method I put together.

    public static string ReadLog()

    {

      StringBuilder returnValue = new StringBuilder();

      EventLog el = new EventLog();

 

      el.Log = “ArcaneCode”;

 

      foreach(EventLogEntry myEntry in el.Entries)

      {

        returnValue.AppendLine(myEntry.Source + “: “

          + myEntry.Message + ” “ + myEntry.TimeGenerated.ToString());

      }

 

      return returnValue.ToString();

    }

The EventLogEntry class has a lot of informative properties, here I’ve grabbed the three most important, Source, Message, and TimeGenerated. Source and Message are just as you wrote to the log. TimeGenerated is important as it lets you know when the message was generated. Not only will this tell you when the user had the issue, you can also use it to limit the amount messages you export.

In a real world situation I would have passed in the code, and probably passed in a date as well to limit the number of entries I returned. But this gives us a good starting point for building our event logger helper class. Stay tuned….

Advertisements