Tuesday, January 12, 2016

Log4net Logging in ASP.NET MVC Application with Autofac IoC Container

In this blog post, I'm trying to discuss log4net logger module integration with ASP.NET MVC application and how it can be integrated with Autofac (an IoC container) to automatic injection of ILog object into Controllers.

Configurations :

  • ASP.NET MVC 5
  • Autofac 3.4.0
  • log4net 2.0.5


Adding log4net into ASP.NET MVC Application


I found following article which discribes the configuration of log4net into ASP.NET MVC application.

http://www.codeproject.com/Articles/823247/How-to-use-Apache-log-net-library-with-ASP-NET-MVC

The steps that included in the above article in short,

Step 1 : Install log4net NuGet package into MyMvcProject.Website
Step 2 : Configure application to use log4net logging configuration by adding to startup.cs file
Step 3 : Add log4net configuration to web.config file
Step 4 : Add logger declaractions to classes which we want to use log4net
Step 5 : Use log.Error to write logging message

In the above "Step 4", we are getting the logger from LogManager.

But, If you are using Autofac as your IoC container for this project, we can do this using Autofac.

Integrating log4net with Autofac


Step 1 : Write Autofac Module

http://docs.autofac.org/en/latest/examples/log4net.html
MyMvcApplication.Website.App_Start.AutofacLoggingModule.cs

Step 2 : Register module into Autofac Config

public static class AutofacConfig {
    public static void ConfigureContainer() {
        var builder = new ContainerBuilder();
        .....
        builder.RegiserModule(new AutofacLoggingModule());
...

Step 3 : Passing ILog into Controller constructor

public class MyController : Controller {
    private readonly log4net.ILog _logger;
    public MyController(ILog logger) {
        _logger = logger;
    }
    public ActionResult MyAction() {
        _logger.Error("Error Message");
    }
}

No comments:

Post a Comment