Configuring Log4net in code using Windsor Installers


Castle provides a great way to structure the setup of your application using the installers. Ninject providers a similar mechanism with modules which you could also use.

Managing configuration was getting pretty painful on my current project, so cutting it down was necessary. Since we don’t need to edit most of the log4net configuration after a build is done, compiling this in is acceptable.

We are using the log4net facility for castle, so this is the first thing we set up.

public class LoggingInstaller : IWindsorInstaller
    public void Install(IWindsorContainer container, IConfigurationStore store)
        if (!container.Kernel.GetFacilities().OfType<LoggingFacility>().Any())
            container.AddFacility("logging", new LoggingFacility(LoggerImplementation.Log4net));

        var root = ((Hierarchy)LogManager.GetRepository()).Root;
        root.Repository.Configured = true;


Next we set up an EventLog appender using the built in object model provided by log4net.

private static IAppender GetEventLogAppender()
    var patternLayout = new PatternLayout("%appdomain [%thread] %-5level - %message%newline [%properties]%newline %exception");

    var eventLogAppender = new EventLogAppender
                                   Name = "Application",
                                   Layout = patternLayout,
                                   ApplicationName = "MyApp",
                                   SecurityContext = NullSecurityContext.Instance
    return eventLogAppender;


And after calling container.Install(new LoggingInstaller()) we have logging without writing a single line of XML!

Older Posts