Logging Using Log4Net in .NET Core Console Application

Log4Net in NET Core Console

Today in this article, we will see how to perform Log4Net in .NET Core Console 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.

Today in this article, we will cover below aspects,

Using Log4NET, logging can be done on the 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 to address 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 is 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 the implementation for HostBuilder and registration for Log4Net logging.

var 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,

<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,

public 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 MyApplication using 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 is an example of file logging created by Log4Net,

Logging Using Log4Net in NET Core Console Application

Log4Net supports different types of logging using the 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 the Console appender as below,

<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 enable 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.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

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