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 { // 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 Trace.Listeners.Add(eventloglistener); } 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.