Writing Exceptions to the Windows Log File

Gold picture Gold · Jul 26, 2009 · Viewed 32.9k times · Source

I'd like to catch my exceptions and log them in the Windows log file. How do I go about opening and writing to the Windows log?

Answer

Doctor Jones picture Doctor Jones · Jul 26, 2009

You can use the System.Diagnostics.EventLog.WriteEntry function to write entries to the event log.

System.Diagnostics.EventLog.WriteEntry("MyEventSource", exception.StackTrace,                  
                                       System.Diagnostics.EventLogEntryType.Warning);

To read event logs you can use the System.Diagnostics.EventLog.GetEventLogs function.

//here's how you get the event logs
var eventLogs = System.Diagnostics.EventLog.GetEventLogs();

foreach(var eventLog in eventLogs)
{    
    //here's how you get the event log entries
    foreach(var logEntry in eventLog.Entries)
    {
        //do something with the entry
    }    
}