简体   繁体   中英

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; } 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.

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());
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM