开发者

When/Where should I create the EventLogSource in Windows Service?

I am developing the Window开发者_开发技巧s Service using C# and .Net framework 4.0.

In order for the Windows Service to write the entry to the EventLog, I need to check and create the Event Log Source if it is not existed.

if (EventLog.SourceExists("MySource") == false)
            EventLog.CreateEventSource("MySource", "MyLog"); 

I am confusing about where I should check and create the Event Log Source. Should I create in the Constructor method of the Windows Service or Constructor method of the Installer Service?

When I googled, I found both ways. So, could you please advise the best practice for me? Thanks.


I think it would be better to add the Event Log Source in the installer, but I would also check to make sure that Event Log Source exists when the service starts up. Also, rather than adding the Event Log Source in the constructor, you probably want to use one of the installer events. I haven't done this before, but I think the AfterInstall event looks like a good place for adding Event Log Sources (see the answer to this question for more info: Automatically start a Windows Service on install).

The reason for using the installer service to add the Event Log Source is because (as @MusiGenesis pointed out) you're more likely to have the security access you need to create the Event Log Source when the application is being installed. When the service is running, it could be set to an account that does not have permissions to create Event Log Sources.

In the service itself, I would check to make sure the Event Log Source exists as well. If it is not present you could try to recreate it, and if that attempt fails then you could take whatever action best suits your needs. For example:

  • Log an error message to the file system somewhere stating that logging is for the service is disabled
  • Throw an exception so the service doesn't start (which should cause Windows to write Event Log entries of its own)
  • Disable logging entirely, etc.

If you check (and try to create the Event Log Source if it does not exist) in the service then you get the added minor benefit of the service being able to tolerate a user or other program deleting the Event Log Source your service is relying on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜