How To Use Log4Net In ASP.NET Core Application

Log4net

Introduction

 
Logging is the heart of an application. It is very important for debugging and troubleshooting, as well as, for smoothness of the application.

With the help of logging, we can have end-to-end visibility for on-premise systems, to only give a fraction of that visibility for cloud-based systems. You can write your logs to a file on a disk or a database, and send an error email.
 

Install NuGet Package for Log4Net


To use Log4Net logging, first you need to add the Log4Net plugin. For adding the plugin, you can do it in two different ways.
  1. Manage NuGet Packages.
  2. NuGet command.
You can find the required NuGet command for Log4Net below.
  1. PM> Install-Package log4net -Version 2.0.8  
Or, you can Click Here.
 

Update Startup file

 
We need to register Log4Net middleware into the startup configure section as below.
  1. public void Configure(IApplicationBuilder app,  
  2.     IHostingEnvironment env, ILoggerFactory loggerFactory)  
  3. {  
  4.     loggerFactory.AddLog4Net();  
  5. }  

Add log4net.config file


We need to click on "Add New" to add a file to your project with the name log4net.config.
 
 
Refer to the below code for log4net.config for logging into the file.
  1. <log4net>  
  2.   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">  
  3.     <lockingmodel type="log4net.Appender.FileAppender+MinimalLock">  
  4.     <file value="logs/">  
  5.     <datepattern value="yyyy-MM-dd hh.'txt'">  
  6.     <staticlogfilename value="false">  
  7.     <appendtofile value="true">  
  8.     <rollingstyle value="Composite">  
  9.     <maxsizerollbackups value="2">  
  10.     <maximumfilesize value="15MB">  
  11.     <layout type="log4net.Layout.PatternLayout">  
  12.       <conversionpattern value="%level  %message  %date">  
  13.     </conversionpattern></layout>  
  14.   </maximumfilesize></maxsizerollbackups></rollingstyle></appendtofile></staticlogfilename></datepattern></file></lockingmodel></appender>  
  15.   <root>  
  16.     <level value="ALL">  
  17.     <appender-ref ref="RollingLogFileAppender">  
  18.   </appender-ref></level></root>  
  19. </log4net>  
Root is neccesary in log4net.config, in which we can define the log level and appender-ref to define appender. For example - FileAppender, ConsoleAppender.
  1. <root>  
  2.     <level value="ALL">  
  3.     <appender-ref ref="RollingLogFileAppender">  
  4. </appender-ref></level></root>  

Layout

In Layout, we can define custom parameters as shown below.
  1. <layout type="log4net.Layout.PatternLayout">  
  2.       <conversionpattern value="%level  %message  %date">  
  3. </conversionpattern></layout>  

Logging Levels


There are seven logging levels.
  • OFF - nothing gets logged (cannot be called)
  • FATAL
  • ERROR
  • WARN
  • INFO
  • DEBUG
  • ALL - everything gets logged (cannot be called)
Different Appender
  • Rolling File Appender - It writes to the output window or the command window.
  • File Appender -This appender will write to a text file.
  • ADO.NET Appender -This appender will write to a Database.
  • Console Appender-This appender performs the same functions as the file appender but with the additional option to store a certain amount of data only before starting a new log file.

Logging Manager of Log4Net

  1.   public static class Logger  
  2.     {  
  3.        
  4.      private static readonly string LOG_CONFIG_FILE = @"log4net.config";  
  5.        
  6.      private static readonly log4net.ILog _log = GetLogger(typeof(Logger));  
  7.        
  8.      public static ILog GetLogger(Type type)  
  9.      {  
  10.          return LogManager.GetLogger(type);  
  11.      }  
  12.      
  13.      public static void Debug(object message)  
  14.      {  
  15.          SetLog4NetConfiguration();  
  16.          _log.Debug(message);  
  17.      }  
  18.    
  19.    private static void SetLog4NetConfiguration()  
  20.      {  
  21.          XmlDocument log4netConfig = new XmlDocument();  
  22.          log4netConfig.Load(File.OpenRead(LOG_CONFIG_FILE));  
  23.    
  24.          var repo = LogManager.CreateRepository(  
  25.              Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));  
  26.    
  27.          log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);  
  28.      }  
  29. }    

Load and Read Log4Net Config File


You need to name your config file to be your assembly name and it needs to have the extension you specify. Here is an example.
  1. Private static void SetLog4NetConfiguration()  
  2.         {  
  3.             XmlDocument log4netConfig = new XmlDocument();  
  4.             log4netConfig.Load(File.OpenRead(LOG_CONFIG_FILE));  
  5.    
  6.             var repo = LogManager.CreateRepository(  
  7.                 Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));  
  8.    
  9.             log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);  
  10.         }     
For more detailed information, visit  this link.
 
Happy Coding!!!