Monday 18 September 2017

Using Log4Net to Log to a File for ASP.NET MVC

There are things I'd like to blog about nearly every week. This week I thought I'd actually get around to doing it, about a simple thing that really should have clearer instructions elsewhere online. We're going to use the Log4Net package to log information in an output file, in an ASP.NET MVC controller. For this example, I used log4net version 2.

First, using the NuGet package manager, install the package for log4net into your project.

Put this line in the file AssemblyInfo.cs:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Put this line in the file global.asax:

log4net.Config.XmlConfigurator.Configure();

Put this in the web.config file:

<configSections>
  ...
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Logs/log.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="100KB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

Rebuild the solution/project.

Put the logging commands in a class method, e.g. a controller:

using log4net;

public class MyController : Controller {
    ILog log = LogManager.GetLogger(typeof(MyController));
    log.Debug("* Debug message");
    log.Warn("* Warning message");
    log.Error("* Error message");
    log.Info("* Information message");
}

Run the application (push F5).

Check the project root for a new folder and a log file, named "log.log". Done!