How To Implement Log4Net In ASP.NET Core Application

How To Use Log4Net In ASP.NET Core Application

Introduction

The logging is the core of an application. It is very important for troubleshooting and debugging, as well as, for smoothness of the application.

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

Install NuGet Package for Log4Net

With the help of Log4Net logging, first, you need to install the Log4Net plugin. after adding the plugin, you can do it in two different ways.

1.Manage NuGet Packages.
2.NuGet command.

here, using following NuGet command for install Log4Net.

PM> Install-Package log4net -Version 2.0.8

Update Startup file

We need to register Log4Net middleware into the startup configure section as below.


public void Configure(IApplicationBuilder app,  
    IHostingEnvironment env, ILoggerFactory loggerFactory)  
{  
    loggerFactory.AddLog4Net();  
}  

Add log4net.config file

We have to click on “Add New” option to add a file to your project with the name log4net.config.

Refer to the following code for log4net.config for logging into the file.

<log4net>  
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">  
    <lockingmodel type="log4net.Appender.FileAppender+MinimalLock">  
    <file value="logs/">  
    <datepattern value="yyyy-MM-dd hh.'txt'">  
    <staticlogfilename value="false">  
    <appendtofile value="true">  
    <rollingstyle value="Composite">  
    <maxsizerollbackups value="2">  
    <maximumfilesize value="15MB">  
    <layout type="log4net.Layout.PatternLayout">  
      <conversionpattern value="%level  %message  %date">  
    </conversionpattern></layout>  
  </maximumfilesize></maxsizerollbackups></rollingstyle></appendtofile></staticlogfilename></datepattern></file></lockingmodel></appender>  
  <root>  
    <level value="ALL">  
    <appender-ref ref="RollingLogFileAppender">  
  </appender-ref></level></root>  
</log4net>

The root is necessary for log4net.config, in which we can characterize the log level and appender-ref to define appender. For example – FileAppender, ConsoleAppender.

<root>  
    <level value="ALL">  
    <appender-ref ref="RollingLogFileAppender">  
</appender-ref></level></root> 

Layout

In Layout, we can define custom parameters as shown following code.

<layout type="log4net.Layout.PatternLayout">  
      <conversionpattern value="%level  %message  %date">  
</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 plays the same functions as the file appender but with the additional option to store a specific amount of data only before beginning a new log file.

Logging Manager of Log4Net

public static class Logger  
    {  
       
     private static readonly string LOG_CONFIG_FILE = @"log4net.config";  
       
     private static readonly log4net.ILog _log = GetLogger(typeof(Logger));  
       
     public static ILog GetLogger(Type type)  
     {  
         return LogManager.GetLogger(type);  
     }  
     
     public static void Debug(object message)  
     {  
         SetLog4NetConfiguration();  
         _log.Debug(message);  
     }  
   
   private static void SetLog4NetConfiguration()  
     {  
         XmlDocument log4netConfig = new XmlDocument();  
         log4netConfig.Load(File.OpenRead(LOG_CONFIG_FILE));  
   
         var repo = LogManager.CreateRepository(  
             Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));  
   
         log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);  
     }  
}  

Load and Read Log4Net Config File

here we need to name of the config file to be your assembly name and it needs to have the extension you specify.


        Private static void SetLog4NetConfiguration()  
        {  
            XmlDocument log4netConfig = new XmlDocument();  
            log4netConfig.Load(File.OpenRead(LOG_CONFIG_FILE));  
   
            var repo = LogManager.CreateRepository(  
                Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));  
   
            log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);  
        } 

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *