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.   
  14.   
  15.         /// <summary>  
  16.         /// Used to log Debug messages in an explicit Debug Logger  
  17.         /// </summary>  
  18.         /// <param name="message">The object message to log</param>  
  19.         public static void Debug(string message)  
  20.         {  
  21.             debugLogger.Debug(message);  
  22.         }  
  23.   
  24.   
  25.         /// <summary>  
  26.         ///  
  27.         /// </summary>  
  28.         /// <param name="message">The object message to log</param>  
  29.         /// <param name="exception">The exception to log, including its stack trace </param>  
  30.         public static void Debug(string message, System.Exception exception)  
  31.         {  
  32.             debugLogger.Debug(message, exception);  
  33.         }  
  34.   
  35.   
  36.         /// <summary>  
  37.         ///  
  38.         /// </summary>  
  39.         /// <param name="message">The object message to log</param>  
  40.         public static void Info(string message)  
  41.         {  
  42.             _instance.monitoringLogger.Info(message);  
  43.         }  
  44.   
  45.   
  46.         /// <summary>  
  47.         ///  
  48.         /// </summary>  
  49.         /// <param name="message">The object message to log</param>  
  50.         /// <param name="exception">The exception to log, including its stack trace </param>  
  51.         public static void Info(string message, System.Exception exception)  
  52.         {  
  53.             _instance.monitoringLogger.Info(message, exception);  
  54.         }  
  55.   
  56.         /// <summary>  
  57.         ///  
  58.         /// </summary>  
  59.         /// <param name="message">The object message to log</param>  
  60.         public static void Warn(string message)  
  61.         {  
  62.             _instance.monitoringLogger.Warn(message);  
  63.         }  
  64.   
  65.         /// <summary>  
  66.         ///  
  67.         /// </summary>  
  68.         /// <param name="message">The object message to log</param>  
  69.         /// <param name="exception">The exception to log, including its stack trace </param>  
  70.         public static void Warn(string message, System.Exception exception)  
  71.         {  
  72.             _instance.monitoringLogger.Warn(message, exception);  
  73.         }  
  74.   
  75.         /// <summary>  
  76.         ///  
  77.         /// </summary>  
  78.         /// <param name="message">The object message to log</param>  
  79.         public static void Error(string message)  
  80.         {  
  81.             _instance.monitoringLogger.Error(message);  
  82.         }  
  83.   
  84.         /// <summary>  
  85.         ///  
  86.         /// </summary>  
  87.         /// <param name="message">The object message to log</param>  
  88.         /// <param name="exception">The exception to log, including its stack trace </param>  
  89.         public static void Error(string message, System.Exception exception)  
  90.         {  
  91.             _instance.monitoringLogger.Error(message, exception);  
  92.         }  
  93.   
  94.   
  95.         /// <summary>  
  96.         ///  
  97.         /// </summary>  
  98.         /// <param name="message">The object message to log</param>  
  99.         public static void Fatal(string message)  
  100.         {  
  101.             _instance.monitoringLogger.Fatal(message);  
  102.         }  
  103.   
  104.         /// <summary>  
  105.         ///  
  106.         /// </summary>  
  107.         /// <param name="message">The object message to log</param>  
  108.         /// <param name="exception">The exception to log, including its stack trace </param>  
  109.         public static void Fatal(string message, System.Exception exception)  
  110.         {  
  111.             _instance.monitoringLogger.Fatal(message, exception);  
  112.         }  
  113.   
  114.           
  115.     }  

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.       }   

Up Next
    Ebook Download
    View all
    Learn
    View all