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)

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,
Thanks beefycode and Wil Peck.

Technorati Tags: ,,


Comments have been disabled for this content.