How can log4net be configured using a System.Configuration.Configuration

1.6k Views Asked by At

I have developed a library that is being consumed by an add-in architecture in another application. My library uses log4net for logging.

This works fine in testing as the location of the app.config can be resolved and log4net is configured using:

log4net.Config.XmlConfigurator.Configure();

When loaded as an add-in it isn't possible to resolve the application configuration using this method.

One option is to configure log4net using a Configuration that is passed in through the add-in architecture. The configuration that can be used is similar to the results of the following:

string asmFile = System.Reflection.Assembly.GetExecutingAssembly().Location;
System.Configuration.Configuration dllConfig = System.Configuration.ConfigurationManager.OpenExeConfiguration(asmFile);

How can the System.Configuration.Configuration be used with the log4net.Config.XmlConfigurator?

I can see the applicable ConfigurationSection from the configuration but can't see a way to easily get the ILoggerRepository or XmlElement required by XmlConfigurator.Configure().

System.Configuration.ConfigurationSection configSection = configuration.GetSection("log4net");
2

There are 2 best solutions below

0
On BEST ANSWER

This is the best I've come up with to date and it doesn't seem particularly robust.

if (configuration.HasFile)
{
        System.IO.FileInfo configFileInfo = new System.IO.FileInfo(configuration.FilePath);
        log4net.Config.XmlConfigurator.Configure(configFileInfo);
}

I did think about using an XmlSerializer writing the configuration to an XmlDocument and then passing that XmlElement into Configure but I couldn't get the configuration to serialize.

1
On

I have no control over how they consume it (other than the API I publish) but need to provide a method for them to configure it.

Our log4net wrapper is in a dll. The projects that use this logging framework just have to add the log4net configuration block in the config file of their webservices/clients.

Besides that the programs have to call this at the startup:

    XmlConfigurator.Configure();