Using multiple configuration files with log4net


Although log4net is most likely one of the most powerful logging libraries for .Net, it has some limitations when it comes to spreading the configuration among multiple files.

 

The use case for it is very common: a set of services wants to share parts of the same configuration (i.e.: sending e-mail in case of error, writing to the DB) but each service wants to write log entries to its own individual file.

 

There are some posts suggesting the implementation, but there is none with a code example. I followed the suggestion from Kid on stackoverflow: to build and in-memory XmlDocument appending different files and let log4net do the rest.

 

My implementation worked on my test case using log4net 1.2.10. I didn’t tested it thoroughly. The idea is to introduce a new section in the application configuration file: log4netMulti. On this new section you may specify from which files the configuration should be read. Example:

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4netMulti" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4netMulti thisConfig="true">
    <file value=".\log4netAdditional.config" />
  </log4netMulti>
  <log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Temp\Test.log"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date	%-5level	[%thread]	%logger	%message%newline" />
      </layout>
    </appender>

    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingFile" />
    </root>
  </log4net>
</configuration>

 

The attribute thisConfig states if the log4net section should also be retrieved on the current configuration file where the log4netMulti section is found.

 

The separate files (in the example log4netAdditional.config) should be regular log4net XML config files.

 

The merge is implemented in the XmlConfigurationMerger.cs class. Unfortunately the XML Configuration classes for log4net are not very extensible, so that I had to do a lot of copy-paste to get it working.

 

In the application code, instead of calling

 

    XmlConfiguration.Configure()

 

one should call

 

    XmlConfigurationMerger.Configure();

 

That’s it. The code can be downloaded from here: XmlConfigurationMerger. Feel free to enhance it or change it if needed, but keep me posted 🙂

 

 

 

Leave a comment

Your email address will not be published. Required fields are marked *