In this asp.net tutorial, we will discuss how to implement Log4Net in ASP.NET Core Application. Step by step I will explain how to use Log4Net in the Asp.Net core application.
ASP.NET core is an open-source, cross-platform, and modular framework for building modern and high-performance applications. .NET Core SDK is a lightweight SDK that includes a minimum set of features required to build an application. We can install other features from NuGet packages.
Also check, Steps to archive log files using NLog with ASP.NET Core.
.NET Core provides programming patterns such as dependency injection, logging, and app configuration. For logging, it includes Microsoft.Extension.Logging package. It will store the logs for display. In this blog, we will learn about Log4Net logging in Asp.net Core.
What is Logging?
Logging is a modern and one of the in-built features in ASP.NET Core application for detecting issues. ASP.NET Core supports a wide variety of logging providers. You can plug in your own frameworks like Log4Net, Elmah, and NLog. Microsoft.Extension.Logging namespace provides supports for simple logging with just a few lines of code.
For ASP.NET Core 1.x, you need to include the dependencies explicitly for your project and these dependencies are built-in for ASP.NET Core 2.x.
Built-in classes and interface in Microsoft.Extension.Logging namespace as follow:
- ILogger
- ILoggerFactory
- LoggerFactory
- ILoggerProvider
ILoggerFactory:
ILoggerFactory interface creates an ILogger instance and also adds an ILoggerProvider instance. In Asp.net Core includes a built-in LoggerFactory class that implements the ILoggerFactory interface.
using Microsoft.Extensions.Logging;
namespace Log4NetExample.Log
{
interface ILoggerFactory : IDisposable
{
ILogger CreateLog(string name);
void LogProvider(ILoggerProvider provider);
}
}
We can use this interface for creating ILogger instance and add ILoggerProvider instance.
ILoggerProvider:
ILoggerProvider creates a suitable ILogger instance and manage it. We can create our own custom logging provider by implementing ILoggerProvider interface.
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Log4NetExample.Log
{
interface ILoggerProvider : IDisposable
{
ILogger CreateLog(string name);
}
}
ILogger:
For logging, ILogger interface includes the methods to store it. There are many extension methods for logging which make it easy.
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Log4NetExample.Log
{
interface ILogger
{
void Log<TState>(LogLevel logLvl, EventId evntId, TState state, Exception exception, Func<TState, Exception, string> formatter);
bool IsEnabled(LogLevel logLvl);
IDisposable BeginScope<TState>(TState state);
}
}
In ILogger, there are 3 methods.
- BeginScope: – It initiates the logical operation scope.
- IsEnabled: – It checks if the log level is enabled or not.
Logging Providers: –
For store and display logs logging providers use a certain medium such as console level, debug level, and event log etc. Microsoft provides an extension or namespace for various logging providers from NuGet package.
Microsoft also team up with the third parties logging framework such as NLog, Serilog, Log4Net, elmah and others.
Basic Configuration Example
Let’s take example using Log4Net.
Step-1: Install Log4Net
PM> Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 2.1.0
Step-2: Update Start up file
Register Log4Net middleware into the startup file configure section.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
{
logger.AddLog4Net();
}
Step 3: Add Log.config File
Add our own custom .config file as illustrates below.
Rolling File Appender:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingmodel type="log4net.Appender.FileAppender+MinimalLock">
<file value="logs/">
<datepattern value="dd-MM-yyyy hh.'txt'">
<staticlogfilename value="false">
<appendtofile value="true">
<rollingstyle value="Composite">
<maxsizerollbackups value="2">
<maximumfilesize value="1GB">
<layout type="log4net.Layout.PatternLayout">
<conversionpattern value="%level %message %date">
</conversionpattern>
</layout>
</maximumfilesize>
</maxsizerollbackups>
</rollingstyle>
</appendtofile>
</staticlogfilename>
</datepattern>
</file>
</lockingmodel>
</appender>
<root>
<level value="ALL">
<appender-ref ref="RollingLogFileAppender">
</appender-ref>
</level>
</root>
</log4net>
Debug Level:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger -%message%newline" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="DebugAppender" />
</root>
</log4net>
We can define log level and Appender-ref into root element. Root element is necessary in the config file.
We have taken here the RollingLogAppender but there are also other types such as FileAppender, ConsoleAppender. This is the basic configuration in the Asp.net Core application. We can add custom configuration using Log4Net Providers as illustrates below.
Custom Configuration Using Log4NetProviders
Step 1: appsettings file Install the package in your Asp.net Core application and add Log4Net in the appsettings.json file.
{
"Log4NetExample": {
"Name": "Test",
"LoggerRepository": "Real",
"OverrideCriticalLevelWith": "Fatal",
"Watch": false,
"UseWebOrAppConfig": false,
"PropertyOverrides": [
{
"XPath": "/log4net/appender[@name='RollingFile']/file",
"Attributes": {
"Value": "overridedFileName.log"
}
},
{
"XPath": "/log4net/appender[@name='RollingFile']/maximumFileSize",
"Attributes": {
"Value": "200MB"
}
},
{
"XPath": "/log4net/appender[@name='RollingFile']/file"
}
]
}
}
Step 2: Place appsetting in program.cs file
Add appsetting.json file in configuration builder method as below. For that, we need to install the Microsoft.Extension.Configuration.Json package.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Log4Net
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
return WebHost.CreateDefaultBuilder(args)
.UseConfiguration(config)
.UseStartup<Startup>();
}
}
}
Step 3: Add log4Net in startup file
Add Log4Net to startup file and configure it.
var loggingOptions = this.Configuration.GetSection("Log4NetCore")
.Get<Log4NetProviderOptions>();
logger. AddLog4Net ();
Complete Startup file as shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Log4Net
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
{
var loggingOptions = this.Configuration.GetSection("Log4NetExample")
.Get<Log4NetProviderOptions>();
logger.AddLog4Net();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
You have seen the Log4NetProviderOptions in Configuration.GetSection method. There are some properties that we have described below.
Properties of Log4NetProviderOptions
- UseWebOrAppConfig – Boolean value that indicate the Log4Net Configuration Section is in the app.config file or in web.config file and its default value is false.
- ExternalConfigurationSetup – This setup indicates that the Log4Net library has been configured outside the extension using XmlConfigurator and its default value is false.
- Watch – This property indicates that the Log4Net.config file will be opened in watch mode and likewise its default value is false.
- PropertyOverrides – During Log4Net initialization it allows to replacement of defined value.
You may like the following tutorials:
- Disable or Hide minimize maximize and close buttons in C#.net windows form
- How to create a folder if not exist in C#.Net
- Why is .NET so popular for web application development?
- How to use jquery modal popup in asp.net
Conclusion
Logging API works with other logging providers. Logging providers display to store the log in console level, debug level, an event log, and other types of the medium. All logging providers reside in Microsoft.Extension.Logging namespace. Such as Logging.Console, Logging.Debug, Logging.EventLog, and others. In this blog, we have seen the basic configuration and custom configuration. Also, we have created log.config using the rolling appender and debug level.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…