The Source and Log properties must be matched
The Log property stores the name of the event log, as visible in the Control Panel > Administrative Tools > Event Viewer applet. Most applications log to the Windows Logs > Application log, the default when you don't assign the Log property. But you can create a custom log for your own app, visible under the "Applications and Services Log" entry.
This info is recorded in the registry at the time you first create the log with CreateEventSource. The Log property must be a match in the future, if it is not then you get this exception. So what you know is that the log in fact already existed, but you once created it with a different log name, "Bar2". Possibly deciding that wasn't a very good name and changing the Log property. Kaboom.
Setting the Log property to an empty string is not a workaround. It will continue to log to the original log name, using the registry to find its name back. You can fix the unwanted registration with Regedit.exe, navigate to HKLM\SYSTEM\CurrentControlSet\Services\EventLog. If you delete the entry then you should also delete the corresponding .evtx file, the File value gives you its path name.
Leaving the log as an empty string solved the error:
Private Sub writeToLog(ByVal msg As String)
Dim evtLog As New EventLog
If Not Diagnostics.EventLog.SourceExists("Bar") Then
Diagnostics.EventLog.CreateEventSource("Bar", "")
End If
evtLog.Source = "Bar"
evtLog.Log = ""
evtLog.WriteEntry(msg)
End Sub
In my case I was assigning a log named "P5-RUN Analytics LOG" to the service named "FSSH P5-RUN Analytics".
Not working: Public Sub New()
' This call is required by the designer.
InitializeComponent()
Try
If Not System.Diagnostics.EventLog.SourceExists("FSSH P5-RUN Analytics") Then
System.Diagnostics.EventLog.CreateEventSource("FSSH P5-RUN Analytics", "P5-RUN Analytics Log")
End If
EventLog1.Source = "FSSH P5-RUN Analytics"
EventLog1.Log = "P5-RUN Analytics Log"
Catch ex As Exception
End Try
End Sub
Working:
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Try
If Not System.Diagnostics.EventLog.SourceExists("P5-RUN Analytics") Then
System.Diagnostics.EventLog.CreateEventSource("P5-RUN Analytics", "P5-RUN Analytics Log")
End If
EventLog1.Source = "P5-RUN Analytics"
EventLog1.Log = "P5-RUN Analytics Log"
Catch ex As Exception
End Try
End Sub
Once I made the first six characters of the service and log match it installed correctly and worked like a charm. It rings a bell from some other article about services conflicting if the first few characters are not in sync (or are duplicated?), but I don't remember where that article was posted.
Last, once I made the changes to my service and log names I cleared the old service/log names from the registry at HKLM\SYSTEM\CurrentControlSet\Service\EventLog before I re-installed my service.