I spent the morning writing a Transport Agent for Exchange 2010 (another story!) to log some emails to disk. As it was on a remote server and remote debugging wasn’t possible, I decided to log some details to the event log. Now this must be the first time I’ve had to write the logging mechanism myself because I’ve never come across this before. When you try to use the EventLog.WriteEntry method you need to pass the source of the message (i.e the application name). So when I did this I get the following exception:
The source was not found, but some or all event logs could not be searched. To create the source, you need permission to read all event logs to make sure that the new source name is unique. Inaccessible logs: Security.
So the meaning of this is that the user the application is running as needs permission to access a certain key in the registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security) in order to find out if the source exists. My application was running as Network Service so I needed to grant that user permission (Full access, not just Read access as specified). This can be acheived as follows:
- Select Start – Run, then enter: regedit
- Navigate/expand to the following key:
- Right click on this entry and select Permissions
- Add the NetworkService user
- Give it Full permission
So now that the user has permission to access the event log, I assumed I would now be able to add logs using the EventLog.WriteEntry method. This however was not the case. It turns out, in order to insert logs into the event log the source needs to exist in the registry. If you have permission you should be able to do the following in C# to add your application to the list:
string sc = "AppName";
This however did not work as I received the following exception:
“Requested registry access is not allowed.”
So the final solution was to manually add the registry keys as follows:
- Locate the following registry subkey:
- Right-click the Application subkey, point to New, and then click Key.
- Type AppName for the key name.
- Close Registry Editor.