Wednesday, June 04, 2008

More Windsor Love: Using log4net integration

Adopting an IoC container has been a software revelation for me. It just keeps on getting better. I just added logging to Suteki Shop simply by doing the following steps (thanks to Sean Chambers for the details)

1. Add a reference to the following Castle Project dlls:

Castle.Facilities.Logging.dll
Castle.Services.Logging.Log4netIntegration.dll

2. Configure the LoggingFacility:

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

3. Add the log4net config file to the root of the web application:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>

  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="sutekishop.log" />
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%level %thread %logger - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>
</configuration>

And that's all. Isn't that cool, now I can simply add a dependcy for ILogger to any service in my application and log to my heart's content.

5 comments:

Flominator said...

Hi there,

thanks for this post. Unfortunately I can't get it to work. My controller still has the Castle.Core.Logging.NullLogger set as Logger property.

Did you test it with the Castle trunk or RC2? Could it maybe be the problem mentioned at this forum post?

Any ideas on how to solve this without having to put this code into every controller?

Thanks,

Flo

FYI: Sean's link no longer works, please use this one.

Flominator said...

I also asked this question at the Castle users group.

Mike Hadlow said...

Hi Flominator,

I'm using the trunk, it definately works. Download the Suteki Shop code and try it for yourself.

Note that I'm doing this in the context of ASP.NET MVC not Monorail so I have no opinion on the Logger member of SmartDispatcherController. I simply inject ILogger wherever I need to use it. Here's an example:

http://code.google.com/p/sutekishop/source/browse/trunk/Suteki.Shop/Suteki.Common/Services/EmailSenderLogger.cs

Mufasa said...

Fluent Castle Windsor config is even easier. You still need to edit the web.config/app.config file with the <log4net> tags, but you don't need to do the <facilities> part of the configuration if you use the following:

MyWindsorContainerInstance
.AddFacility<LoggingFacility>(f => f
.LogUsing(LoggerImplementation.Log4net)
.WithAppConfig());

Antony Scott said...

Excellent post. It helped me greatly simplify my logging config and setup code.