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…

Add comment