Wednesday, 15 October 2014

How to Use Log4net with ASP.NET MVC 5 for Logging

Log4net is an open source library that allows .NET applications to log output to a variety of sources.

Log4net provides a simple mechanism for logging information to a variety of sources. 
Information is logged via one or more loggers. These loggers provide 5 levels of logging:
  1. Debug
  2. Information
  3. Warnings
  4. Error
  5. Fatal
Here I will be walking through the step by step in implementing logging functionality using log4net framework in an ASP.NET MVC 5 application.

I am using Visual Studio Express 2013 for Web as my development environment targeting .NET framework 4.5.1

Step 1:

Open Visual Studio 2013 for Web and create a new ASP.NET Web application selecting MVC template.

Step 2: 

Now We need to add reference of log4net DLL using NuGet package manager.






Step 3:

Next, we need to configure our application to use log4net logging framework. Add the below line in yourstartup.cs file in ASP.NET MVC5 Solution folder. The below line of code provides information about log4net configuration file.

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




Step 4:

Next, add the below section to web.config file.

<configSections>
    <!-- Add log4net config section-->
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,     log4net" />
  </configSections>

  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <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>

Step 5:

Next modify Global.asax.cs and add the below code inside Application_Start() method.

readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 6:

Use the logger.Error() method to log messages when needed.


Step 7:

Run an application and we can see the log file generated under the logs folder under the application root directory as configured in the web config file.




DONE :)


1 comment: