Tweaking log4net Settings Programmatically

A few months ago, I had to dynamically add a log4net appender at runtime.  Now I find myself in another log4net situation.  I need to modify the configuration of my appenders at runtime.

My client requires all files generated by our applications to be saved to a specific location.  This location is determined at runtime.  Therefore, I want my FileAppenders to log their data to this specific location – but I won't know the location until runtime so I can't add it to the XML configuration file I'm using.

No problem.  Bing is my new friend and returned a couple of hits.  I made a few tweaks to their LINQ queries and created a generic extension method for ILoggerRepository (just a hunch that I might want this functionality somewhere else in the future – sorry YAGNI fans):

public static void ModifyAppenders<T>(this ILoggerRepository repository, Action<T> modify) where T:log4net.Appender.AppenderSkeleton
{
    var appenders = from appender in log4net.LogManager.GetRepository().GetAppenders()
                        where appender is T
                        select appender as T;
 
    foreach (var appender in appenders)
    {
        modify(appender);
        appender.ActivateOptions();
    }
}

Now I can easily add the proper directory prefix to all of my FileAppenders at runtime:

log4net.LogManager.GetRepository().ModifyAppenders<FileAppender>(a =>
                {
                    a.File = Path.Combine(settings.ConfigDirectory,
                                          Path.GetFileName(a.File));
                });
Thanks beefycode and Wil Peck.

Technorati Tags: ,,
Published Monday, May 03, 2010 3:58 PM by PSteele
Filed under: , ,

Comments

# re: Tweaking log4net Settings Programmatically

Very helpful, thanks.

One thought, in the LINQ query you could use the repository argument from the extension method instead of calling log4net.LogManager.GetRepository() again.

Tuesday, June 22, 2010 7:38 PM by Daniel Ballinger

# re: Tweaking log4net Settings Programmatically

Ah yes -- very cool!  Thanks for catching that Daniel!

Wednesday, June 23, 2010 10:31 AM by PSteele