Trace to Windows EventLog

Windows 7 Event Viewer Icon

In dotNET we use the System.Diagnostics.Trace and some TraceListerner implementation to log information, warnings and errors. My applications use the Windows Eventlog with the EventLogTraceListener. But what if your custom EventSource is not available and your user has no administrative privileges? This problem emerged yesterday with a hard crash of my application.

The TraceListener was added from code so I added some extra logic to prevent the application from crashing. It checks wether it can trace to the EventSource by writing to the EventLogTraceListener. This tries to create the eventsource if it doesn’t exist.

using System.Diagnostics;

/// ... somewhere in my startup code ...
var eventLog = new EventLog("Application");
// convention: use the name of the application as the source
eventLog.Source = System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
eventloglistener = new EventLogTraceListener(eventLog);
eventloglistener.Filter = new EventTypeFilter(SourceLevels.Error);

    // Try to write to it, if the source exists this will succeed else the framework
    // will try to create it which can result in an exception on insufficient privileges
    eventloglistener.WriteLine("Testing eventsource is available");
    // We're okay add to the listeners
catch (Exception ex)
    eventloglistener = null;
    // fallback scenario: notify user about missing eventsource

Almost the same code can be used to check the TraceListeners from the configuration file. Just try to trace some text from within a try-catch block.

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.