How To Configure Log4net In .NET 7 API

Introduction

In this article, I'm going to explain how we can configure log4net in a .NET 7 API project. Before we go deep dive into how to configure log4net, let's first understand why we need to configure log4net in our project. let's first discuss why we need log4net.

Why do we need Log4net?

When we need a production-level application or an efficient product that needs to be improved day by day, then the question is how we can achieve improvement. The answer is, "by knowing our mistakes ", because we can't improve if we don't know where we need improvement. In our application, these things are done very efficiently by a logging framework, now the question is what is the logging framework? the answer is,  "logging framework is responsible for logging errors and other information that we may need for improvement". The next question is there are a bunch of logging frameworks available logging why do we need log4net? the answer is, "log4net is one of the most efficient logging frameworks and is owned by apache". I think that the requirements are clear now, let's go forward to the next question how we can configure log4net in a .NET7 API.

Please follow these steps to configure log4net,

The project of some learners may have already been created but some people will be about to start so, Let's start from the beginning.

Step 1

Open visual studio, at least Visual Studio 2022 if you are going to implement it into.NET 7 API otherwise you can use a lower version, first, click on create a new project.

Configure Log4net In .NET 7 API
Figure-Create new project

Step 2

Next, choose ASP.NET Core Web API as a project template and click on the next button.

 Configure Log4net In .NET 7 API
Figure-Choosing Asp.NetCore API as the project template

Step 3

Next, we see the configuration screen. Here you need to enter the project name and click on the next button.

Configure Log4net In .NET 7 API
Figure-Project name

Step 4

Next, we need an additional information window. Here we need to choose the target framework of our application here I have chosen.NET 7.0 and click on the create button.

Configure Log4net In .NET 7 API
Figure-Target Framework

Step 5

Now our project template is ready with a weather forecast controller. First we need to install the log4net package in our project. People who have already created the project can start from here. To install log4net you need to open the NuGet package manager. To open the NuGet package manager right-click on the project name and click on the NuGet package Manager

Configure Log4net In .NET 7 API
Figure-Open NuGet Package Manager

Step 6

Now just click on the browse button and type lo4net in the search box.

Configure Log4net In .NET 7 API
Figure-browsing for Log4net

Here we can see that log4net has already 149M downloads as it is a popular logging framework. Now just tap on log4net and click on install, it will ask for permission and then will be installed in your project.

After installation, we need to configure it with our project. The main part of the configuration starts from here. log4net is not a .NET library so it'll not be configured automatically, we need to configure it manually. Here we need a configuration file containing that information of configuration like where you want to store your log, the name of your log file, and the format of your file, etc. To do all these configurations we need a configuration file, let's move to our next step.

Step 7

Right-click on the project name and click on Add then click on New Item

Configure Log4net In .NET 7 API
Figure-adding new file

Then search for configuration and choose Web Configuration File and enter the file name then click on add button

Configure Log4net In .NET 7 API
Figure-adding configuration file

Now we need to add configuration settings in this file let's move toward to next step.

Step 8

Here we add this code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<log4net>
		<appender name="RollingLogFileAppender"
				  type="log4net.Appender.RollingFileAppender">
			<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
			<file value="location put here ie D:\TestLog\" />
			<datePattern value="yyyy-MM-dd.'txt'"/>
			<staticLogFileName value="false"/>
			<appendToFile value="true"/>
			<rollingStyle value="Date"/>
			<maxSizeRollBackups value="100"/>
			<maximumFileSize value="15MB"/>
			<layout type="log4net.Layout.PatternLayout">
				<conversionPattern
					value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
			</layout>
		</appender>
		<root>
			<level value="INFO"/>
			<appender-ref ref="RollingLogFileAppender"/>
		</root>
	</log4net>
</configuration>

In this code, I have defined the setting related to logging like file-name, file-location, RollingLogFileAppender, etc that are required. You can also define the size of your file as I have defined 15 MB.

<maximumFileSize value="15MB"/> 

You can increase or decrease the file size depending on your requirement. Now most of the things are ready we just need to load these settings and use the logger.

Step 9

Now we need to load the .config file and log the exception and related information. I'm going to use the WeatherForecastController. I have created a method with the name private void LogError(string message) to load the .config file and log the error.

private  void LogError(string message)
{
    var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
    XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
    ILog _logger = LogManager.GetLogger(typeof(LoggerManager));
    _logger.Info(message);
}

Here you have to put the same name that you entered at the time of adding the configuration file

XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

like I have entered log4net.config. Now you just need to call this method and pass the exception. Here I have created an exception manually by adding a method private int div(int x). This method generates a divide by zero type exception

private int div(int x)
{
  return x / 0;
}

Now I have called this method under the try block and called that LogError method in the catch block, and it will log the exception

[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable < WeatherForecast > Get() {
  try {
    int x = div(50);
    return Enumerable.Range(1, 5).Select(index =>new WeatherForecast {
      Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
      TemperatureC = Random.Shared.Next( - 20, 55),
      Summary = Summaries[Random.Shared.Next(Summaries.Length)]

    }).ToArray();
  }
  catch(Exception ex) {
    LogError(ex.Message);
    throw;
  }
}

When we run the program and execute the following call we get an exception

Configure Log4net In .NET 7 API
Figure-Exception

Now if we check our log file then the log message would be written with the given format, let's have a look

Configure Log4net In .NET 7 API
Figure-Log information

Conclusion

In this article, we have created a log4net-configured API project. This one was a normal project structure if you want to use it on your product then I would suggest creating an Interface and defining logging methods there and then using them in your project after implementation.


Similar Articles