Logging events to existing sources in a log is fine, very straightforward to code and provides a useful way to track problems in your applications. Creating a new log source on the other hand is a different matter.
Most articles on the subject will usually provide very similar example code (check out MSDN), which checks if the source exists and if not, creates it. Something like…
Imports System.Diagnostics
Sub WriteLog(ByVal myEventMsg As String, ByVal myLog As String)
If (Not EventLog.SourceExists(myLog)) Then
EventLog.CreateEventSource(myLog, myLog)
End If
Dim ELog As New EventLog()
ELog.Source = myLog
ELog.WriteEntry(myEventMsg)
End Sub
I found no problem with this as long as the source existed, but as soon as I chose to create a new source the SourceExists method only triggered an exception. The error message given by the exception is ‘Requested registry access is not allowed.’, for which there is a useful Microsoft knowledge base article (329291). The second approach to solving this issue described in the article, although a little more time consuming, is the path I chose.
So, if the source exists then SourceExists returns ‘True’ as expected, but collapses in a spineless heap if it doesn’t. Is it because this is part of a web application, running under the ASPNET user which does not have rights to query the registry? Not quite, as the MS knowledge base article states:
According to this the ASPNET user has no right to ‘create’ an event source, so the application should fail on the CreateEventSource line. But alas, as debugging has shown me many times this is not the case, it always fails on the SourceExists call in the ‘if’ condition.
Could this be a .NET issue? Who knows…
