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 Package manager command for install Log4Net.

PM> Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 3.1.0

here, using following NuGet .NET CLI command for install Log4Net.

dotnet add package Microsoft.Extensions.Logging.Log4Net.AspNetCore --version 3.1.0

Update Startup file

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

using Microsoft.Extensions.Logging;

public class Startup
{
    //...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //...
        loggerFactory.AddLog4Net(); // << Add this line
        app.UseMvc();
        //...
    }
} 

Add log4net.config file

We have to click on the 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.

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="example.log" />
     <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="DebugAppender" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

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

  <root>
    <level value="ALL"/>
    <appender-ref ref="DebugAppender" />
    <appender-ref ref="RollingFile" />
  </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 *