Properties in log4net config

Another little log4net gem! You are probably aware of the use of property in conversion patterns in log4net using the PatternLayout, but did you know you could use them in configuration? Well I didn’t..

My goal was to push a rolling log file path file into the config file, so that we could avoid having to maintain multiple config files across services. So choosing the global context for properties (there are numerous contexts) I just added the file path before calling Configure in my case using the XmlConfigurator:

1 log4net.GlobalContext.Properties["LogFilePath"] = logFilePath;

In config I can reference this named property using the conversion pattern syntax in the file value:

1 ... 2   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> 3     <file type="log4net.Util.PatternString" value="%property{LogFilePath}"/> 4 ... 5

The key part to note is the type of “log4net.Util.PatternString” associated to the file element allowing the conversion syntax to be interpolated – pretty sweet.

Use a custom log4net PatternConverter via config

We should be now all know how configurable and extensible log4net is – we have been using for years after all. Recently though I struggled to find out how to use a custom PatternConverter in a pattern layout using configuration.

So with a simple PatternConverter such as:

1 public class TestPatternConverter : PatternConverter 2 { 3 protected override void Convert(TextWriter writer, object state) 4 { 5 writer.Write(“test”); 6 } 7 } 8

Which you can blatantly see does do much other than write out “test” – but this is just to demonstrate the concept. The documentation describes adding the converter in code using the AddConverter operation – but no mention of how to do that in config?

1 ... 2 <layout type="log4net.Layout.PatternLayout"> 3       <conversionPattern value="%writeTest %message" /> 4       <converter> 5         <name value="writeTest" /> 6         <type value="Demo.Logging.TestPatternConverter, Demo.Logging" /> 7       </converter>    8     </layout> 9 ...

Pretty straight forward really – within the PatternLayout add a converter tag naming it and offering the qualified type name. You can then reference the named item just as you would any other pattern in your layout. So helpfully here we would get “test” written before the log message! Obviously it is possible to imagine more useful scenarios…