Search code examples
c#windowsloggingevent-log

Writing Exceptions to the Windows Log File


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?


Solution

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