Marshall Marshall - 1 month ago 15
C# Question

Log4net and windows service. What else should I do to make this work

Please help me, I want to run log4net on my windows service. And it is simply - mission impossible.

First of all, with Win forms - work great.

Here is what I do with windows service:

Add to assembly:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

My config:

<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="log-file.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c: %m%n" />
<level value="ALL" />
<appender-ref ref="LogFileAppender" />

My class:

public class LogProvider
private ILog _Log;

public LogProvider(string className)
_Log = LogManager.GetLogger(className);

public void Info(object message)

And in main program:

using log4net;
using log4net.Config;


private LogProvider _logProvider;


_logProvider = new LogProvider("Test");


If it possible, please show me sample project - because, this code above is about 100 version or more. I start to believe that this is impossible to use log4net using windows service.


So, about permissions:
Actually I get an exception, about permissions. I fix this with this line (requirePermission="false"):

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>

Now, It still not working, with no exception.

This is my final exec code:

protected override void OnStart(string[] args)

LogProvider lp = new LogProvider("asd");
catch (Exception ex)
System.IO.FileInfo _file;
System.IO.StreamWriter _writer;
_file = new System.IO.FileInfo("D:\\Log\\asdCatch.txt");
_writer = _file.CreateText();
_writer.WriteLine("[" + DateTime.Now.ToString() + "] Init Log");
_writer.WriteLine("[" + DateTime.Now.ToString() + "] " + ex.ToString());


Now I'm really confused, I've created another windows service and it's working - without that line with permission. OMG, this is weird.

OK, I've got it. I don't know how did this happened, but I found that line in my app.config:

<NetFx40_LegacySecurityPolicy enabled="true"/>

I'm working on 15-subproject program and seriously, I don't know where it came from:/


We had a problem because the services runtime directory is C:\Windows\System or C:\Windows\System32. Therefore the log4net.config has to be in your system dir which is not desirable or you have to provide the path to your log4net.config file.