Use Log4net In ASP.NET MVC Application

You may have read several articles on how to use log4net; however,  this article explains how you can use it without having to initialize several times.

Log4Net is a framework for implementing logging mechanisms. It is an open source framework.

Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers are provided at the below levels of logging:

  • Debug
  • Information
  • Warnings
  • Error
  • Fatal

Now let’s begin with implementation.

Add log4net Package

For this, you need to install log4net from NuGet Package Manager  to your ASP.NET MVC project as per the below screen.

log4net

Add Global.asax for loading log4net  configuration

Once installation is done, you need to add the below code in Application_Start() of  Global.asax

  1. log4net.Config.XmlConfigurator.Configure();  

Add log4net in config file

No,w open web.config and enter the following details.

  1. <configSections>  
  2.   <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />  
  3. </configSections>  
  4.   
  5. t;log4net>  
  6.   <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">  
  7.     <file value="C:\Temp\nSightsLog.log" />  
  8.     <appendToFile value="true" />  
  9.     <maximumFileSize value="500KB" />  
  10.     <maxSizeRollBackups value="2" />  
  11.     <layout type="log4net.Layout.PatternLayout">  
  12.       <conversionPattern value="%date %level %logger - %message%newline" />  
  13.     </layout>  
  14.   </appender>  
  15.   <root>  
  16.     <level value="All" />  
  17.     <appender-ref ref="RollingFile" />  
  18.   </root>  
  19. </log4net>  

Implementing in specific file for accessing throughout application

Add a class Log.cs in the Utilities folder. 

Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.

  1. private Log()  
  2. {  
  3.     monitoringLogger = LogManager.GetLogger("MonitoringLogger");  
  4.     debugLogger = LogManager.GetLogger("DebugLogger");  
  5. }  

Here, you need to create Debug(), Error(), Info(), Warn(), Fatal() methods which will call respective methods from Log4 net.

Below is a sample. 

  1. public class Log  
  2. {  
  3.     private static readonly Log _instance = new Log();  
  4.     protected ILog monitoringLogger;  
  5.     protected static ILog debugLogger;  
  6.   
  7.     private Log()  
  8.     {  
  9.         monitoringLogger = LogManager.GetLogger("MonitoringLogger");  
  10.         debugLogger = LogManager.GetLogger("DebugLogger");  
  11.     }  
  12.  
  13.     /// <summary>  
  14.     /// Used to log Debug messages in an explicit Debug Logger  
  15.     /// </summary>  
  16.     /// <param name="message">The object message to log</param>  
  17.     public static void Debug(string message)  
  18.     {  
  19.         debugLogger.Debug(message);  
  20.     }
  21.     /// <summary>  
  22.     ///  
  23.     /// </summary>  
  24.     /// <param name="message">The object message to log</param>  
  25.     /// <param name="exception">The exception to log, including its stack trace </param>  
  26.     public static void Debug(string message, System.Exception exception)  
  27.     {  
  28.         debugLogger.Debug(message, exception);  
  29.     }
  30.     /// <summary>  
  31.     ///  
  32.     /// </summary>  
  33.     /// <param name="message">The object message to log</param>  
  34.     public static void Info(string message)  
  35.     {  
  36.         _instance.monitoringLogger.Info(message);  
  37.     }
  38.     /// <summary>  
  39.     ///  
  40.     /// </summary>  
  41.     /// <param name="message">The object message to log</param>  
  42.     /// <param name="exception">The exception to log, including its stack trace </param>  
  43.     public static void Info(string message, System.Exception exception)  
  44.     {  
  45.         _instance.monitoringLogger.Info(message, exception);  
  46.     }  
  47.   
  48.     /// <summary>  
  49.     ///  
  50.     /// </summary>  
  51.     /// <param name="message">The object message to log</param>  
  52.     public static void Warn(string message)  
  53.     {  
  54.         _instance.monitoringLogger.Warn(message);  
  55.     }  
  56.   
  57.     /// <summary>  
  58.     ///  
  59.     /// </summary>  
  60.     /// <param name="message">The object message to log</param>  
  61.     /// <param name="exception">The exception to log, including its stack trace </param>  
  62.     public static void Warn(string message, System.Exception exception)  
  63.     {  
  64.         _instance.monitoringLogger.Warn(message, exception);  
  65.     }  
  66.   
  67.     /// <summary>  
  68.     ///  
  69.     /// </summary>  
  70.     /// <param name="message">The object message to log</param>  
  71.     public static void Error(string message)  
  72.     {  
  73.         _instance.monitoringLogger.Error(message);  
  74.     }  
  75.   
  76.     /// <summary>  
  77.     ///  
  78.     /// </summary>  
  79.     /// <param name="message">The object message to log</param>  
  80.     /// <param name="exception">The exception to log, including its stack trace </param>  
  81.     public static void Error(string message, System.Exception exception)  
  82.     {  
  83.         _instance.monitoringLogger.Error(message, exception);  
  84.     }
  85.     /// <summary>  
  86.     ///  
  87.     /// </summary>  
  88.     /// <param name="message">The object message to log</param>  
  89.     public static void Fatal(string message)  
  90.     {  
  91.         _instance.monitoringLogger.Fatal(message);  
  92.     }  
  93.   
  94.     /// <summary>  
  95.     ///  
  96.     /// </summary>  
  97.     /// <param name="message">The object message to log</param>  
  98.     /// <param name="exception">The exception to log, including its stack trace </param>  
  99.     public static void Fatal(string message, System.Exception exception)  
  100.     {  
  101.         _instance.monitoringLogger.Fatal(message, exception);  
  102.     }      
  103. }  

Now, you need to call the logger class that logs directly into your action method.

  1. public ActionResult Login()  
  2. {  
  3.     //This is for example , we need to remove this code later  
  4.     Log.Info("Login-page started...");  
  5.   
  6.     // Boolean msg = CheckSetupType();  
  7.     return View();  
  8. }