简体   繁体   English

如何在 dot net core 中设置 log4net 以记录所有未处理的异常?

[英]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?我正在使用此处建议的实现将 log4net 添加到当前的点网核心项目https://thecodebuzz.com/log4net-file-logging-console-logging-asp-net-core/ (这是使用 Microsoft.Extensions.Logging .Log4Net.AspNetCore),如何设置 log4net 来记录所有未处理的异常? 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:我尝试像这样添加 LogFilter class,再加上 Startup.cs 中的此更改:

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

in the ConfigureServices method as well as the public ILogger Logger { get; }在 ConfigureServices 方法以及public ILogger Logger { get; } public ILogger Logger { get; } property, but the error I get is about _logger being null in my LogFilter class. public ILogger Logger { get; }属性,但我得到的错误是关于 _logger 在我的 LogFilter class 中是 null。

Later update (side note):稍后更新(旁注):

In a controller, I can get _logger to work by adding a property: private readonly ILogger _logger;在 controller 中,我可以通过添加一个属性来让 _logger 工作: 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.并将其传递给构造函数: ILogger<MyController> logger ,但在 FilterClass 中遵循与构造函数中的ILogger<ControllerBase> logger相同的方法不起作用。 Error is the same as mentioned above.错误与上面提到的相同。

To log any unhandled exception in .net Core you must create an exception filter, something like this:要在 .net 核心中记录任何未处理的异常,您必须创建一个异常过滤器,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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