Search code examples
logginglog4netcastle-windsorlog4net-configuration

Logging with Castle.Facilities.Logging and log4net


I'm trying to get log4net integration for Castle Windsor working. I wrote my class with an public property of type ILogger and took the configuration in my app.config like following.

<configuration>
  <configsections>
    <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configsections>

  <castle>
    <facilities>
      <facility id="logging" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" loggingApi="log4net" />
    </facilities>
    <components>
      <component id="form1" type="WinFormsActiveRecordSample.Form1, WinFormsActiveRecordSample" />
    </components>
  </castle>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="FileAppender" />
    </root>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="main.log" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date{dd.MM.yy HH:mm:ss} %-5level %logger - %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

In my eyes this should be working, but it doesn't. When I set loggingApi="console" it logs correctly. When I change it to log4net it does nothing. The log4net configuration was taken from another project where the block is working. What do I have to do that the log file is used? Must there be a special log4net configuration?

Thanks for any hint

Boris


Solution

  • Move your log4net configuration to a separate file log4net.config, then refer that file from the facility configuration:

    <facility id="loggingfacility" configfile="log4net.config" loggingapi="log4net" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"/>
    

    If you want to have your log4net configuration in a section of your app.config:

    public class MyLog4NetFactory: Log4netFactory {
        public MyLog4NetFactory() {
            XmlConfigurator.Configure();
        }
    
        public override ILogger Create(String name) {
            ILog log = LogManager.GetLogger(name);
            return new Log4netLogger(log.Logger, this);
        }
    
        public override ILogger Create(String name, LoggerLevel level) {
            throw new NotSupportedException("Logger levels cannot be set at runtime. Please review your configuration file.");
        }
    }
    

    then register the facility as:

    <facility 
      id="loggingfacility" 
      loggingapi="custom" 
      customLoggerFactory="[fully qualified type name of MyLog4NetFactory]" 
      type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"/>