Using Log4net To Log Exceptions In ASP.NET

Log4net is an amazing library to help us log in to our applications in a petty simple way. 

To start with log4net in ASP.NET we need to install the nuget package.

dotnet add package log4net

Then we need to include the log4net.config file. This is an XML file that contains all the settings for our Log. We can specify the format, filename, maximum file size, and others. 

This is an example,

<?xml version="1.0" encoding="utf-8" ?>
            <level value="ALL" />
            <appender-ref ref="RollingLogFileAppender" />
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="api.log" />
            <appendToFile value="true" />
            <rollingStyle value="Composite" />
            <maxSizeRollBackups value="5" />
            <maximumFileSize value="10MB" />
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%date %5level %class - MESSAGE: %message%newline"/>
  • file: Name of the file created with the log
  • level: Used to Specify the level error to save in the log. Other levels are going to be ignored and ALL includes all the levels.
  • maximumFileSize: Maximum size of the log file if the log exceeds this limit, log4net is going to create a new file. 

This is an example where the file is located,

Now, we need to set up the log in the program.cs class to start the log when the API starts.  

public static void Main(string[] args)
    var host = CreateHostBuilder(args).Build();
    ILoggerRepository repository = log4net.LogManager.GetRepository(Assembly.GetEntryAssembly());
    var fileInfo = new FileInfo(@"log4net.config");
    log4net.Config.XmlConfigurator.Configure(repository, fileInfo);    

Finally, we are ready to create a filter in our project in order to catch all the possible exceptions in our application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using log4net;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Api.Attributes
   public class LogFilterAttribute : ExceptionFilterAttribute
        ILog logger;
        public LogFilterAttribute()
            logger =  LogManager.GetLogger(typeof(LogFilterAttribute));
        public override void OnException(ExceptionContext Context)
            logger.Error(Context.Exception.Message + " - "  + Context.Exception.StackTrace);

Add to the services the filter created:

 services.AddControllersWithViews(p=> p.Filters.Add(new LogFilterAttribute()));

Now, all the exceptions are going to be saved in the log file. This log is on Api\bin\Debug\net5.0

Using Log4net to Log exceptions in ASP.NET

Log Example

Using Log4net to Log exceptions in ASP.NET

You still can use the .NET Logger class when you want to log something manually.