Ben Scheirman

These fickle bits...

Menu

Changing Log4net Connection String at Runtime

On my current project, we log with log4net.  This project is still kicking, and I still love using it.  It is a bit dated though, and there are things that probably should work out of the box, but just don’t.

One of those things is the AdoNetAppender’s connection string.  There’s no built-in way of making this use a connection string from your <connectionStrings> section of your config file.

I came across this post, which helped me solve the problem, but the post is 4 years old and the code sample didn’t quite work. 

Here is an updated snippet that does work with the latest version of log4net:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void SetAdoNetAppenderConnectionStrings(string connectionStringKey)
{
  var hier = (Hierarchy)LogManager.GetRepository();
  if (hier != null)
  {
    var appenders = hier.GetAppenders().OfType<adonetappender>();
    foreach (var appender in appenders)
    {
      appender.ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringKey].ConnectionString;
      appender.ActivateOptions();
    }
  }
}

That works nicely, and allows me to remove the connectionString element from the AdoNetAppender’s configuration.

One small caveat:  log4net tries to open the connection at runtime to make sure the database connection string is valid.  You’ll see a message like “Unable to open a database connection to []” which you can safely ignore.  If it really bothers you, then you can add a valid connection string here, but that sort of defeats the purpose of DRY.

Comments