31 July 2008

Event Logging

Here's a quick method to log exceptions to the event log:
private void LogException(Exception exception){
EventLogPermission permissions = new EventLogPermission(EventLogPermissionAccess.Administer, ".");

using (EventLog log = new EventLog("Application")){

if (!EventLog.SourceExists("MySourceName")){
EventLog.CreateEventSource("MySourceName", "Application");

log.Source = "MySourceName";
log.WriteEntry(exception.ToString(), EventLogEntryType.Error);
A couple of things to note:
  • The using statement makes sure the EventLog object is disposed without fail
  • The EventLogPermission permits this callee to create an event source if required and to write to the event log

No comments: