Thursday 30 August 2007

How to pass parameters set at runtime to the log4net configuration

Today I learnt that it is possible to pass parameters set at runtime to the log4net configuration sections.
We could in example put the following appender in our log4net configuration section:

<appender name="SystemAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="C:\Logs\%property{LogFileName}.log" />
<appendToFile value="true" />
<maximumFileSize value="1000KB"/>
<maxSizeRollBackups value="2"/>
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %thread %logger - %message%newline"/>

Did you noticed the attributes of the file element? Togheter with the usual value, we got also a type, set to log4net.Util.PatternString, and if you double check, you will notice also the value is a bit unusual: part of the string is a %property{LogFileName} substring.
Now, that substring is telling to the log4net to look for a property called LogFileName in its ThreadContext. If you set that property before the call to XmlConfigurator.Configure, as in the following snippet, you will be able to programmatically set it at runtime:

log4net.ThreadContext.Properties["LogFileName"] = "MyApplication";

This will set your log file to C:\Logs\MyApplication.log.
This approach can be useful in many scenarios, but probably not so efficient if you wish to multiplex the log entries to different files, because everytime you set the LogFileName property, you need to call again XmlConfigurator.Configure().

Thanks to Max Leifer to show us this technic :)

No comments: