Search code examples
c#exceptionlogging.net-coreunhandled

How can I set up log4net in dot net core to log all unhandled exceptions?


I am using the implementation suggested here for adding log4net to current dot net core project, https://thecodebuzz.com/log4net-file-logging-console-logging-asp-net-core/ (this is using Microsoft.Extensions.Logging.Log4Net.AspNetCore), how can log4net be set up to log all unhandled exceptions? I haven't figured out a way to do this. Any pointers please?

Later edit:

public class LogFilter : ExceptionFilterAttribute
{
    public readonly ILogger _logger;

    public LogFilter(ILogger logger)
    {
        _logger = logger;
    }

    // public Logger Logger { get; set; }
    public override void OnException(ExceptionContext Context)
    {
        //Log what you need here, the exception is in Context.Exception
        _logger.LogError(Context.Exception, null);

        Context.ExceptionHandled = true;
    }
}

I tried adding a LogFilter class like this, coupled with this change in Startup.cs:

services.AddMvc(o =>
{
    o.Filters.Add(new LogFilter(Logger));
});

in the ConfigureServices method as well as the public ILogger Logger { get; } property, but the error I get is about _logger being null in my LogFilter class.

Later update (side note):

In a controller, I can get _logger to work by adding a property: private readonly ILogger _logger; and passing it in the constructor: ILogger<MyController> logger but in the FilterClass following the same approach with ILogger<ControllerBase> logger in the constructor doesn't work. Error is the same as mentioned above.


Solution

  • To log any unhandled exception in .net Core you must create an exception filter, something like this:

    public class LogFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext Context)
        {
            //Log what you need here, the exception is in Context.Exception
    
            Context.ExceptionHandled = true;
        }
    }
    

    And register the filter:

    public void ConfigureServices(IServiceCollection Services)
    {
        // Add framework services.
        Services.AddMvc(o =>
        {
            o.Filters.Add(new LogFilter());
        });
    }