A Day In The Lyf

…the lyf so short, the craft so longe to lerne

log4net Connection String Blues

We use log4net as our production logger, which has proven to be tremendously flexible. However, one problem I ran into was configuring the AdoNetAppender that logs to the database. It expects the connection string to be defined in the configuration file, which I didn’t want to do since it was already defined in our NHibernate config file.

This proved to be a relatively easy fix (found here):

private void  SetConnectionStrings()
    Hierarchy hierarchy = LogManager.GetRepository() as Hierarchy;
    if (hierarchy == null)

    using (UnitOfWork unitOfWork = new UnitOfWork())
        foreach (IAppender appender in hierarchy.GetAppenders())
            AdoNetAppender dbAppender = appender as AdoNetAppender;
            if (dbAppender != null)
                dbAppender.ConnectionString = unitOfWork.ConnectionString;

However, the problem is that log4net whined to standard error about not having the connection string defined. The result was that any console application had its output garbled (including our tests, since some of them used the production logger).

The solution turned out to be going ahead and putting a connection string in the config file, but making it obviously invalid (e.g., “<ignore>”). Then, when the logger is configured, temporarily redirect standard error:

public void ConfigureLogger()
    FileInfo file = new FileInfo(ConfigUtils.GetFilePath(“log4net.config”));
    TextWriter stdErr = Console.Error;
    Console.SetError(new StreamWriter(new MemoryStream()));
    ServiceRegistry.Logger = new Log4NetLogger();



Written by Brandon Byars

September 9, 2007 at 10:01 pm

Posted in .NET

Tagged with

%d bloggers like this: