.NET Core : Logging with Log4NET in .NET Core application

There are tons of newly created logging engines for .NET Core. Log4Net is stable, old school technology in the market. Consider using newer logging technologies, such as NLog or Serilog. But if you want to use this engine, you can make it work.

Start with the Microsoft’s tutorial, “Logging in .NET Core”. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-5.0

Install log4Net NuGet Package, and Microsoft.Extensions.Logging.Log4Net.AspNetCore package.

Install-Package log4Net
Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore

Make changes in your Program.cs file. In the CreateHostBuilder method, configure logging with the following code:

                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddConsole();
                    logging.AddLog4Net();
                })

If the “AddLog4Net” method call is unrecognized by IntelliSense, make sure you have installed the Logging extension NuGet package mentioned above.

Add a new file to your project, and name it log4Net.config. The template should be used is Web Configuration file.

Make changes in the newly generated file, here you can configure the applications logging. I’ve skipped Console logging, Microsoft’s console logger visualize logs much greater. You can learn configuring Log4Net more at https://logging.apache.org/log4net/release/manual/configuration.html
A quick start configuration example:

<?xml version="1.0" encoding="utf-8"?>
<log4net>
	<root>
		<level value="ALL" />
		<appender-ref ref="file" />
	</root>
	<appender name="file" type="log4net.Appender.RollingFileAppender">
		<file value="myapp.log" />
		<appendToFile value="true" />
		<rollingStyle value="Size" />
		<maxSizeRollBackups value="5" />
		<maximumFileSize value="10MB" />
		<staticLogFileName value="true" />
		<layout type="log4net.Layout.PatternLayout">
			<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
		</layout>
	</appender>
</log4net>

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.