A good logging library is an important addition to our projects: we can use it for testing, and debugging purposes; once a project enters the production stage, it will help us to detect, and troubleshoot anomalous situations.

There are many debugging libraries for C# (the one that I use regularly is log4net a C# port of the log4j Apache’s library): it offers various levels of logging, the possibility to work with different appenders (logging to different mediums such as file, console, etc), and it is highly configurable (using a configuration file).

The process to add log4net to an ASP.Net MVC project  differs a bit of the one used in other type of C# solutions. So let’s review the steps one has to follow to successfully add logging support to our ASP.Net MVC project using log4net.

Adding log4net to an ASP.NET MVC project

1. Install log4net NuGet package.

2. Add a log4net section inside the tag configSections of your web.config like this:

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

3. In the same web.config add the configuration for the log inside the tag log4net, for example:

<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="C:\\LOGS\" />
    <datePattern value="'MyAPP.log_'yyyy-MM-dd'.log'" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <appendToFile value="true" />
    <staticLogFileName value="false" />
    <layout type="log4net.Layout.PatternLayout, log4net">
      <conversionPattern value="%date [%thread] %-5level %logger [%method] - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

4. In the Application_Start() method of your global.asax file you need add this call, so that log4net reads the configuration that you set up in the web.config file:

log4net.Config.XmlConfigurator.Configure();

The full method looks like this:

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            log4net.Config.XmlConfigurator.Configure();
        }
    }

5. And now we are ready to start logging information. For starters we need to define a logger variable:

private static readonly ILog log =  log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

For example, here is how we add some log messages to our controller:

public class HomeController : Controller
    {
        private static readonly ILog log =  log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public ActionResult Main()
        {
            log.Error("This could be an error");
            return View();
        }
    }

In the log file we have specified above, we should have this entry once we run our application:

2017-07-26 22:03:35,199 [7] ERROR WebApplication1.Controllers.HomeController [Main] - This could be an error

Move log4net configuration to an external file

The web.config file can grow quite a bit. So it is easier to keep the lognet configuration in a separate file.

1. Add to your project a new xml file, lets call it, for example, Log.config. In this file we will place the contents of the tag (remember to start the file with the line xml version=”1.0″ …).

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="C:\\LOGS\" />
    <datePattern value="'MyAPP.log_'yyyy-MM-dd'.log'" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <appendToFile value="true" />
    <staticLogFileName value="false" />
    <layout type="log4net.Layout.PatternLayout, log4net">
      <conversionPattern value="%date [%thread] %-5level %logger [%method] - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="INFO" />
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

2. Now we got our log4net configuration in the Log.config file. What we need to do now it is to find a way to let our program know where to look for the configuration.

We will do that by adding the following tag to our web.config file, in the section appSettings:

  <add key="log4net.Config" value="Log.config"/>

And that is all that it is needed; it is important to remember this second step, otherwise the configuration settings will be ignored.

Troubleshooting: or who watches the watchman

If you followed the steps described in the previous section, and still there isn’t any logging happening, chances are that something went wrong in the configuration process.

Add the following line to your web.config, once again in the section appSettings:

  <add key="log4net.Internal.Debug" value="true"/>

This will enable log4net’s internal logging, and send extra debugging messages to the Visual Studio console that can help you to find what has gone wrong.

More resources

Now you have added a powerful logging library to your ASP.NET MVC project, there are various resources in Internet, that will help you to make good use of all its strengths.

You can start for this tutorial on log4net, where you will learn the basics the different logging levels available, how to configure a RollingFileAppender so that you can split the log file into smaller files, use of filters, etc.

The 10 commandments of logging is a quite interesting article that gives tips, and advice on the overall logging strategy to use in your software, to create useful, meaningful logs.

Hope it was of help. If you found this post useful, you can subscribe to my blog (click at the follow button at the bottom) so you can be notified of new posts.

Advertisements