log4net – How to change settings of an appender at runtime

I found this awesome blog post about 4 tips on log4net from the year 2005.

Since the code is out to date I post here my update.

2 nice things:

  1. I use EntityConnectionStringBuilder to extract the database connection string from an entity framework connection string
  2. If my log4net connectionstring, holds {auto} , we replace it, otherwise we wont
    (so that we can change the logging database, if we want to)

protected void Application_Start(object sender, EventArgs e)
        {
            // change the connectionString setting of the ADONetAppender at runtime 
            // to the value of the connectionstring appSetting in the web.config: 
            
            // Get the Hierarchy object that organizes the loggers
            Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy;

            if (hier != null)
            {
                // Get ADONetAppender
                var adoAppender =
                    (AdoNetAppender)hier.GetAppenders().Where(
                        appender => appender.Name.Equals("ADONetAppender", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();

                if (adoAppender != null)
                {
                    // Change only when the auto setting is set
                    if (adoAppender.ConnectionString.Contains("{auto}"))
                    {
                        adoAppender.ConnectionString = 
                            ExtractConnectionStringFromEntityConnectionString(
                                GetEntitiyConnectionStringFromWebConfig());

                        //refresh settings of appender
                        adoAppender.ActivateOptions(); 
                    }
                }
            }
        }

        private string ExtractConnectionStringFromEntityConnectionString(string entityConnectionString)
        {
            // create a entity connection string from the input
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(entityConnectionString);

            // read the db connectionstring
            return entityBuilder.ProviderConnectionString;
        }

LogManager.GetLoggerRepository is obsolete. Thanks Resharper ;-) . Use: GetRepository()

 

Now up to write some unit tests around this!

image

Latest Posts

Popular Posts

 
Google Analytics Alternative