Configure log4net logging framework for ASP.NET MVC

This post will provide a short overview of the steps needed to integrate the Apache log4net logging framework to an ASP.NET MVC Web application:

  1. Include the log4net in your MVC project, you can use the NuGet package manager (Alternatively, you can also download and add the log4net.dll reference manually):
    PM> install-package Log4Net
  2. Add the following tags to the MVC Web.config file:
    <configuration>
      <configSections>
        [...]
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
      </configSections>
      [...]
      <log4net>
        <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
          <file value="C:\Temp\log4net.log" />
          <appendToFile value="true" />
          <maximumFileSize value="500KB" />
          <maxSizeRollBackups value="2" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date %level %logger - %message%newline" />
          </layout>
        </appender>
        <root>
          <level value="All" />
          <appender-ref ref="RollingFile" />
        </root>
      </log4net>
    </configuration>
  3. Add the following line to the AssemblyInfo.cs file:
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
  4. To test the log4net logging 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.Info("Action Index has been fired.");
      [...]
    }
  5. To use relative path for the log file instead of the absolute path, change the following tag in the web.config: From:
    <file value="C:\Logs\log4net.log" />
    To (But first you should create a new folder under your MVC application and name it as "Logs"):
    <file value="Logs/log4net.log" />

Post a Comment

Previous Post Next Post