Log4Net And .NET Core

Log4Net and .NET Core
Image by Robin Joshua on Unsplash

Introduction

In general, most developers would agree that logs are the heart of the application.

Due to many reasons, I’ve seen that they have given this opinion because it helps us, developers, for debugging and troubleshooting. As well as maintaining the smooth operation of the application in production.

If you have been programming for a while now and you have tried and seen some logging frameworks and you want to have a least a good review of what logging is, you come to the right place.

In this article, we’ll discuss what a logging framework is using Log4Net. We’ll also show its benefits and different types of log levels.

Moreover, in the latter part, we’ll show some code samples.

Ok, let’s get started.

What is Log4net?

It is a logging framework tool that can significantly reduce the workload associated with logs.

Moreover, it is one of the most widely used logging frameworks within the .NET applications maintained by Apache.

Furthermore, it is based on the popular Java logging framework Log4j.

Is Log4Net Can be Used on .NET Core 6?

Yes, you can still use Log4Net to help you output log statements of text files, databases, and other destinations using .NET Core 6 by installing log4net version 2.0.7 (this version targets .NET Standard) and beyond via NuGet Packages.

Benefits of a Logging Framework?

Using a logging framework handles many important inconvenient aspects of logging such as where to log, whether to append to an existing file or create a new one, how the formatting of the message log will look like, and many more.

Moreover, another critical issue that a logging framework handles for developers is where the logs should be redirected or targeted.

That’s why a logging framework helps you easily redirect your logs to different locations by simply having or changing your configuration.

Furthermore, once you have built your log infrastructure within your .NET/.NET Core application and without changing any of your code you can write your logs to a file disks, a database, an existing log management system, or potentially dozens of other locations.

Therefore, log files are one of the assets of a developer. It is because logs give you a more defined format and details. Just imagine when something goes wrong in production in most cases developers check the logs or at least request the logs from the system admin of the production servers.

Use Different Types of Log Levels

When dealing with logs we must be able to determine the appropriate type of log to use.

The usage of Debug, Info, Warning, Error, and Fatal are different from one another.

However, it is obvious that with the names given to them you’ll be able to know where and when to use them. Just imagine if you have used Debug in every aspect of the application’s code.

Here are the Log4Net levels: All, Debug, Info, Warn, Error, Fatal, and Off.

Types of Appender

  • 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.
  • File Appender – appends the log messages to a certain file.
  • ADO.NET Appender - log messages to a certain database such as MS SQL Server, MS Access, Oracle, IBMDB2, SQLite, etc.
  • 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.

Log4Net and .NET Core Console Application

Step 1

Let’s create a blank solution, you can name it anything you want but, in my case, I named it “Log4NetSample.Solution” without the quotes.

See the screenshots below on how to create a new blank solution.

Log4Net and .NET Core

Log4Net and .NET Core

Log4Net and .NET Core

Step 2

Let’s add a new class library and in my case, I named it “Log4NetSample.LogUtility” without the quotes.

See the screenshots below on how to add a new project to a solution.

Log4Net and .NET Core

Log4Net and .NET Core

Log4Net and .NET Core

Log4Net and .NET Core

Step 3

Within the project “Log4NetSample.LogUtility”, the objective is to create a small utility class that will leverage the Log4Net library.

Moreover, we’ll just focus on the Debug, Info, and Error.

However, before we start showing the code, we need to install a NuGet Package “log4net”.

OK, so open the Package Manager Console and install log4net version 2.0.15.

Log4Net and .NET Core.

After the installation, you can now add the following code below.

Note: You can copy and paste the code to the "Class1.cs" and rename it later to "Logger.cs". Or you can remove the file "Class1.cs" and then create a new class "Logger.cs" then copy and paste the code below.

using log4net;
using System.Reflection;
namespace Log4NetSample.LogUtility {
    public interface ILogger {
        void Debug(string message);
        void Info(string message);
        void Error(string message, Exception ? ex = null);
    }
    public class Logger: ILogger {
        private readonly ILog _logger;
        public Logger() {
            this._logger = LogManager.GetLogger(MethodBase.GetCurrentMethod()?.DeclaringType);
        }
        public void Debug(string message) {
            this._logger?.Debug(message);
        }
        public void Info(string message) {
            this._logger?.Info(message);
        }
        public void Error(string message, Exception ? ex = null) {
            this._logger?.Error(message, ex?.InnerException);
        }
    }
}

This won’t be useful yet, but we’ll see the use of this later.

In the next step let’s create a new console application project and use the log utility that we have created.

Step 4

Let’s create the console application first and install the log4net via NuGet Package Manager.

Log4Net and .NET Core

I named the console application project “Log4NetSample.ConsoleApp” without the quotes.

Log4Net and .NET Core

Log4Net and .NET Core

Log4Net and .NET Core

Don’t forget to set the startup project to “Log4NetSample.ConsoleApp”. Before we start coding, we need to install a NuGet Package “log4net” with the console application project.

Log4Net and .NET Core

Step 5

In this section, we’ll see how we can add a configuration file for us to interact with the log4net’s different appenders.

Log4Net and .NET Core

In the configuration file we’ll only focus on the log4net.Appender.RollingFileAppender and log4net.Appender.ManagedColoredConsoleAppender.

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

Before we check the tags of the configuration file, don’t forget to change the property “Copy to Output Directory” set to “Copy always”.

Log4Net and .NET Core

Within the configuration there are two important sections <root> and <appender>.

The <root> is where the level of logs is defined and what should be displayed and what appender to use.

The <appender-ref/> is a tag that has an attribute ref which sets to the type of appender we have defined in the tag section.

The <appender> tag has 2 attributes name and type.

The type can be set to a certain type of appender, like for example the first appender we have which is set to log4net.Appender.ManagedColoredConsoleAppender which means we want to use the ManageColoredConsoleAppender which logs events to the standard output stream with colors and by default output is written to the console’s standard output stream.

Step 6

Finally, a code sample using the log4net and the simple log utility that we have created.

Moreover, in the latter of this step, we’ll show the output of the console application and the sample output of the file.

using log4net;
using log4net.Config;
using Log4NetSample.LogUtility;
using System.Reflection;
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4netconfig.config"));
var demo = new Logger();
demo.Info("Starting the console application");
try {
    demo.Debug($ "Starting {MethodBase.GetCurrentMethod()?.DeclaringType}");
    throw new Exception("Sample Error inside the try catch block code");
} catch (Exception ex) {
    demo.Error(ex.Message, ex.InnerException);
}
demo.Debug("Waiting for user input");
Console.ReadLine();
demo.Info("Ending application");

Output

For the console output, see the screenshot below.

Log4Net and .NET Core

And of course, we have configured to have a file-appender, see the output for main.log.

Log4Net and .NET Core

Conclusion

In this post, we have discussed what is Log4net, its benefits, the different types of log levels, and types of appenders and we have shown a working sample to show how to use Log4net in a .NET Core 6 console application.

I hope you have enjoyed this article as much as I have enjoyed writing it.

Stay tuned for more and don't forget to download the attached project-source code.

Until next time, happy programming!