Using log4net with a Windows service

  • Thread starter Thread starter Gerald Aden
  • Start date Start date
G

Gerald Aden

I am using log4net 1.1 and am having a really hard time getting it to work
with a C# Windows service.

Here is the code I put in the Main:

StreamWriter writer = new StreamWriter("c:\\tmp\\log4net.log");

writer.AutoFlush = true;

Console.SetOut(writer);

log4net.helpers.LogLog.SetInternalDebugging(true);

log4net.Config.DOMConfigurator.ConfigureAndWatch(new
System.IO.FileInfo("log4net.config"));

_logger = LogManager.GetLogger(typeof(Service));

_logger.Debug("Running service.");

I don't get the log4net debug output or the logged message.

If I put the very same code into a console application I see both the
log4net debug output and the logged message. Has anyone used log4net in a
Windows service? Are there any special considerations?

Thanks for you time.

Gerald
 
Hello Gerald,

Well, this probably wont work, because a Windows Service wont have a Console.

Look at setting up a LogFileAppender (which is the way that this should be
done anyway). In your app.config, do something like:

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

log4net"/>
</configSections>

<log4net>
<root>
<level value="ALL" />
<appender-ref ref="FileAppender" />
</root>

<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt"/>
<appendToFile value="true"/>

<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c [%x] &lt;%X{auth}>
- %m%n" />
</layout>
</appender>
</log4net>

Make sure you add the [assembly: log4net.Config.DOMConfigurator(Watch=true)]
attribute to your assemblyinfo.cs file.

That will replace all of the code that you have except for:

_logger = LogManager.GetLogger(typeof(Service));
_logger.Debug("Running service.");
 
Back
Top