Log4Net in a Windows Service

Requirement: I want a Windows Service

Seems easy, but wut – no logfile created!

The help at  Apache FAQ: Why doesn’t the logging in my service work? is fine, but maybe I just skipped over it – it took me a while to figure out that the problem of log4net not showing any results (meaning: writing out a logfile) was related to the windows service not being able to find my application.config file (cause the service was called from a different location than my output dir).

The Apache FAQ suggests using AppDomain.BaseDirectory which unfortunately fails when I want to initialize the logger in the Services Main() method due to Main being static. Copying the app.config to lets say c: and using

log4net.Config.XmlConfigurator.Configure(new FileInfo("c:\app.config"));

works, but isnt exactly what we want – at least it should use some temporary or application-specific dir in %appdata%

edit: time to bang head against something again – a failure in the configuration file caused the problem.

This line allowed logging to a client-specific directory:

<file type="log4net.Util.PatternString" value="%env{APPDATA}\ConSense\Logs\ConSense.Sensors.Service.ConsoleStart.Log.txt" />

Btw – a very nice introduction to Log4Net:

 

==============================================================================

偶的解决方法:只要将service的启动用户改为LocalSystem 就可以了。推测可能原因是Network Service帐号权限不足,不能在本地目录中创建log文件。

引文来源  Log4Net in a Windows Service | ConSense Project