Wednesday, August 13, 2008

log4net: hostname in logfile's name

I recently came across the problem that while using the excellent log4net tool with fileappender I needed to programatically include the machine name in the logfile's name (the application's config is on a shared disk area, so hard-wiring the nodename was not an option). Thanks to the log4net team, since version 1.2.9 this can be achieved via the PatternString and the ConversionPattern classes. Let's see a working c# example.

This is what you should put into your application's config (Web.config in my case) to the <log4net> section:

<appender name="SomeLogFileAppender" type="log4net.Appender.FileAppender">
<file type="log4net.Util.PatternString" >
<name value="hostname" />
value="MyNamespace.MySubNamespace.HostnamePatternConverter,MyNamespace" />
value="debuglog-%hostname{LocalApplicationData}.txt" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level - %message%newline" />

And then the code snippet which implements HostnamePatternConverter:

using log4net;
using System;

namespace MyNamespace.MySubNamespace {


public class HostnamePatternConverter : log4net.Util.PatternConverter
protected override void Convert(TextWriter writer, object state)



No comments: