Logging Using Log4Net in .NET Core application

162 0

Today in this article, we will see how to perform File/Rolling File logging and Console logging using Log4Net in Console .NET Core application.

We shall be leveraging DI( Dependency Injection) framework to inject the Log4Net Logger object into the mini IoC DI container in a .NET Core Console application.

Using Log4NET, logging can be done on Console or File or Rolling file easily. It also provides flexibility to control log layout and log as per log level types in the application.

As we understood File/Rolling File logging provider is still not available through the .NET Core framework. However, we need to rely on external solutions and today we shall see how to use Log4Net addressing the same requirement.

Microsoft recommends using a third-party logger framework like a Serlilog or Log4Net or NLog for other high-end logging requirements like Database or File/Rolling File logging.

Getting started

Create a .NET Core Console application,

Logging Using Log4Net in .NET Core Console Application


Log4Net is a Nuget package and available through the NuGet packages manager.

Please use the latest available version.

Please add below NuGet Packages,

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

Or

Please install the package through Nuget Package Manager,

Logging Using Log4Net in .NET Core Console Application

Creating Generic HostBuilder

We shall be using Generic HostBuilder to register the Log4Net logger instance.

The HostBuilder class is available from the following namespace,

using Microsoft.Extensions.Hosting;

Please install the NuGet package from Nuget Package manager or PMC,

PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.1

Please create Generic HosBuilder and register the dependencies like Log4Net and other business dependencies.

See below implementation for HostBuilder and registration for Log4Net logging.

1234567891011121314var builder = new HostBuilder()                .ConfigureServices((hostContext, services) =>                {                    services.AddTransient<MyApplication>();                 })                .ConfigureLogging(logBuilder =>                {                    logBuilder.SetMinimumLevel(LogLevel.Trace);                    logBuilder.AddLog4Net("log4net.config");                 }).UseConsoleLifetime();             var host = builder.Build();

Above we are configuring the logging using Log4Net.config file. Please add a new Log4Net.config file if not available.

Below is the complete implementation for IoC container,

Logging Using Log4Net in .NET Core Console Application

File Logging Appender in Console Application

If you wish to enable only File/Rolling File logging appender, please use the File appender in the log4net.config file as below,

Sample log4net.config file used is as below,

123456789101112131415<log4net>  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">    <file value="TheCodeBuzz.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="TRACE" />    <appender-ref ref="RollingFile" />  </root></log4net>

Please see below sample implementation of MyApplication,

1234567891011121314151617public class MyApplication    {        private readonly ILogger _logger;        public MyApplication(ILogger<MyApplication> logger)        {            _logger = logger;        }         internal void Run()        {            _logger.LogInformation("Application {applicationEvent} at {dateTime}", "Started", DateTime.UtcNow);             //Perform Business logic here             _logger.LogInformation("Application {applicationEvent} at {dateTime}", "Ended", DateTime.UtcNow);        }    }

Here we are using logging in MyApplicationusing regular ILogger Interface. Here below MyApplication uses the ILogger interface using Dependency injection.

Logging Using Log4Net in .NET Core Console Application

Let’s execute the code and verify the generated file.

The log file will be created in the project output directory and logging will be captured as shown below figure.

Below shows an example of file logging created by Log4Net,

Logging Using Log4Net in .NET Core Console Application

Log4Net supports different types of logging using logging appender. Please use the required appenders as appropriate.

Console Logging using Console Appender

If you wish to enable only Console logging with the customized format of log message please use Console appender as below,

123456789<appender name="Console" type="log4net.Appender.ConsoleAppender">    <layout type="log4net.Layout.PatternLayout">      <!-- Pattern to output the caller's file name and line number -->      <conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />    </layout>  </appender>     <appender-ref ref="ConsoleAppender" />  </root>

You can also use multiple appenders if needed.

That’s all, Hope this article was helpful.

Summary

Log4Net helps us enabling logging in a few simple steps and addresses the file-based and other types of logging requirements easily. Today in this article we saw how to use logging in .NET Core console application

I found this article interesting that i decided to share. Here is the source

Related Post