ASP.NET MVC: How to use Apache’s log4net logging framework


This blog post will give an short overview of the steps needed to integrate the Apache log4net logging framework to an ASP.NET MVC 3 Web application.
For simplicity, we are starting from a new ASP.NET MVC 3 Web application and choose the “Internet Application” template to have some default controllers and views. To include the log4net one could use the NuGet extension manager:

PM> install-package Log4Net

Alternatively, you can also download and add the log4net.dll reference manually.

An easy way to configure the log4net is to add the following tags to your Web.config file:


  
    
[...]

The example configuration above adds an appender that logs all kind of messages to the file C:\Temp\log4net.log. In a real world project you should use a more detailed configuration. For example, one could configure an appender that sends log messages with level ERROR or FATAL to the system administrator.

The last thing we have to do is to tell log4net to read the XML configuration. One could either edit the Global.asax.cs file and add the following lines:

protected void Application_Start()
{
  [...]
  log4net.Config.XmlConfigurator.Configure();
}

or instead of editing the Global.asax.cs file one could add the following line to the AssemblyInfo.cs file:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]

To test the log4net logging we add the following lines of code to the HomeController.cs file:

private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));
[...]
public ActionResult Index()
{
  log.Debug("HomeController.Index() was called");
  [...]
}

After launching the project and browsing to the Home page log4net creates the log file C:\Temp\log4net.log and adds the following log message for each request:

2011-05-03 21:11:19,294 DEBUG MVC3_Log4Net.Controllers.HomeController - HomeController.Index() was called
,

4 responses to “ASP.NET MVC: How to use Apache’s log4net logging framework”

  1. You are a life saver man…. Thanks a ton for this.. I have been scratching head since 2hrs now… Thank you very much..

Leave a Reply

Your email address will not be published. Required fields are marked *