Intigration of logging in C# .Net Core with Log4Net

Kailash Chandra Behera | Saturday, September 16, 2023

Introduction

In my previous blog posts given below, I explained how to log in C# application(.Net Framework ) with Log4Net. Here in this blog post, we will explore how to work with log4net in.net core.

  1. How to use log4net in C#
  2. log4net ASP NET MVC Example
  3. log4net Configuration for Multiple Files
  4. How to use log4net in WPF

Getting Started

Implementing logging for .net core is as same as like .Net Framework but there is a bit difference. The difference is, addition one step you need to do to add the config file manually. In the console application in net core, we will demonstrate all the code.

Install Log4Net

Log4Net in .net core is not a inbuild library of Microsoft .Net Framework, it is a third party library. To use it we need to install it from Microsoft package manager that is NuGet. The following stpes explains how to download it.

  • Go to the solution explorer of your project and right click on project name.
  • Click on the Manage NuGet Package from the context menu, the Package Manager window will be opened.
  • Browse Log4Net from the Package Manager window, you will get the NLog.Web.AspNetCore as shown in the below Image.
  • Install the lastest stable version of Log4Net by clicking the install button On the right pan.

Add .Net Core Configuration File for Log4Net

In the above of this blog post, I have mentioned that an additional step is requred in .Net core application or projects for Log4Net. Unlike the configuration details of Log4Net used in .Net Framework are not added directly in the configuration file in .net core project. The following steps guides how to add .net core configuration file in to project that will interact with the log4net’s different appenders.

  • Right click on the project from solution explorer.
  • Go to Add then click on New Item, the new Add New Item window will be display.
  • Select the Application Configuration File then enter name of the config file in the Name field to "Log4NetConfig" then click OK.
  • Right click on the new added Configuration file and click on the properties.
  • In the properties window, go to property "Copy to Output Directory" and set its value "Copy always".
  • Open the configuration file-> copy the below codes from <log4net> and <log4net/> and paste it in between the start and end configuration element like below.
 <configuration>  
  <log4net>  
   <root>  
    <level value="ALL" />  
    <appender-ref ref="file" />  
   </root>  
   <appender name="file" type="log4net.Appender.FileAppender">  
    <file value="main.log" />  
    <appendToFile value="true" />  
    <rollingStyle value="Size" />  
    <maxSizeRollBackups value="5" />  
    <maximumFileSize value="25MB" />  
    <staticLogFileName value="true" />  
    <layout type="log4net.Layout.PatternLayout">  
     <conversionPattern value="%date [%thread] %level %logger.%method[%line] - %message%newline" />  
    </layout>  
   </appender>  
  </log4net>  
 </configuration>  

You may notice in the above config file only two measure elements are use that is Level and Appender. The log levels decide which type of logs messages to be write and the appender decide where the .net core logs to be write.

Log4Net Log Levels

Log4Net Levels decide which type of log messages to be write for example if you want to write only the information then you need to set the level to Info. By default it's value is ALL. All log messages written through log4net must be assigned one of the five among following log4net level:

  • Debug:- Will print message at the time of debugging project only.
  • Info:- Used to record information type message.
  • Warn:- Used to log warnings.
  • Error:- Used to record errors or exception.
  • Fatal:- Used to print fatal error messages.

Log4Net Appenders

Appenders decides where to write the .net core logs. for example File Appender or ADO.NET Appender. The file appender will write all the .Net Core Logs to a file and the ADO.NET appender will write to mentioned databae. following appenders are supported by Log4Net.

  1. Rolling File Appender – makes a log file depending on your filters, allowing you to have log files based on dates (one file per day) or have the file split into small chunks when it reaches a certain size.
  2. File Appender – appends the log messages to a certain file.
  3. ADO.NET Appender - log messages to a certain database such as MS SQL Server, MS Access, Oracle, IBMDB2, SQLite, etc.
  4. Console Appender – log messages are normally sent to the console output stream. In other words, you’ll be able to see the logs immediately on the console window.ASB

Console Application in .Net Core with Log4Net

The following code shows how to use the log4net in console application in .net core. Note that there is no separete code for different appenders. Code is same for all but appenders are different as per own requirement or based on the target. copy the codes and past in program file in your console application.

 var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());  
       XmlConfigurator.Configure(logRepository, new FileInfo("Log4netConfig.config"));  
       ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType);  
       _logger.Info("Starting console application");  
       try  
       {  
         _logger.Debug("Starting {MethodBase.GetCurrentMethod()?.DeclaringType}");  
         _logger.Warn("Warning message");  
         throw new Exception("Error Sample inside the try catch block code");  
       }  
       catch (Exception ex)  
       {  
         _logger.Error(ex.Message, ex.InnerException);  
       }  
       Console.WriteLine("Hello World!");  
       //Console.ReadLine();  
       _logger.Info("Ending application");  

.Net Core Logging to File

FileAppender and RollingFileAppender are used to write the .Net core logs into a file, below configuration codes are example of RollingFileAppender. The configuration example given in the begining of the blog post is example of FileAppender.

 <log4net>  
   <root>  
    <level value="ALL" />  
    <appender-ref ref="file" />  
   </root>  
   <appender name="file" type="log4net.Appender.RollingFileAppender">  
    <file value="logs.log" />  
    <appendToFile value="true" />  
    <rollingStyle value="Size" />  
    <maxSizeRollBackups value="5" />  
    <maximumFileSize value="25MB" />  
    <staticLogFileName value="true" />  
    <layout type="log4net.Layout.PatternLayout">  
     <conversionPattern value="%date [%thread] %level %logger.%method[%line] - %message%newline" />  
    </layout>  
   </appender>  
  </log4net>  

The above configuration contains file appender that will write logs in a file called logs.log.

C# Log Console Appender

 <log4net>  
   <root>  
    <level value="ALL" />  
    <appender-ref ref="console" />  
   </root>  
   <appender name="console" type="log4net.Appender.ManagedColoredConsoleAppender">  
    <mapping>  
     <level value="INFO" />  
     <forecolor value="Green" />  
    </mapping>  
    <mapping>  
     <level value="WARN" />  
     <forecolor value="Yellow" />  
    </mapping>  
    <mapping>  
     <level value="ERROR" />  
     <forecolor value="Red" />  
    </mapping>  
    <mapping>  
     <level value="DEBUG" />  
     <forecolor value="Blue" />  
    </mapping>  
    <layout type="log4net.Layout.PatternLayout">  
     <conversionPattern value="%date %level %logger.%method[%line] - %message%newline" />  
    </layout>  
   </appender>    
  </log4net>  

We have set the value of name to "Console". Notice this is the same as the value of ref in the root tag. The value of type has been set to log4net.Appener.ConsoleAppender. This means that will write logs messages in Console window. There are many different Appenders including ColorConsole, which allows for the console to display the log in different colors based on the its level.

Console Application in .Net Core with multiple appender

Multiple appenders also can be used to write .net core logs. Below configuration settings shows how to use multiple appenders. you can use the below configuration in your project directly.Copy the below xml contents and past in your config file.

 <?xml version="1.0" encoding="utf-8" ?>  
 <configuration>  
  <log4net>  
   <root>  
    <level value="ALL" />  
    <appender-ref ref="console" />  
    <appender-ref ref="file" />  
   </root>  
   <appender name="console" type="log4net.Appender.ManagedColoredConsoleAppender">  
    <mapping>  
     <level value="INFO" />  
     <forecolor value="Green" />  
    </mapping>  
    <mapping>  
     <level value="WARN" />  
     <forecolor value="Yellow" />  
    </mapping>  
    <mapping>  
     <level value="ERROR" />  
     <forecolor value="Red" />  
    </mapping>  
    <mapping>  
     <level value="DEBUG" />  
     <forecolor value="Blue" />  
    </mapping>  
    <layout type="log4net.Layout.PatternLayout">  
     <conversionPattern value="%date %level %logger.%method[%line] - %message%newline" />  
    </layout>  
   </appender>  
   <appender name="file" type="log4net.Appender.RollingFileAppender">  
    <file value="main.log" />  
    <appendToFile value="true" />  
    <rollingStyle value="Size" />  
    <maxSizeRollBackups value="5" />  
    <maximumFileSize value="25MB" />  
    <staticLogFileName value="true" />  
    <layout type="log4net.Layout.PatternLayout">  
     <conversionPattern value="%date [%thread] %level %logger.%method[%line] - %message%newline" />  
    </layout>  
   </appender>  
  </log4net>  
 </configuration>  

Thanks


No comments: