【问题标题】:Can ILogger be trusted to catch / log ALL uncaught exceptions?可以信任 ILogger 来捕获/记录所有未捕获的异常吗?
【发布时间】:2019-06-27 15:17:00
【问题描述】:

标题说明一切。

有没有,如果有,什么时候,ILogger 不会记录未捕获的异常?

我问的原因是;我正在配置 Rollbar,它会记录所有 ILogger 日志以及未捕获的异常。这将创建 2 个日志。我正在考虑禁用 Rollbar 的日志未捕获异常,并相信 ILogger 已经捕获了它们。

这个问题与 Rollbar 无关 :)

【问题讨论】:

  • 应该。然而,ILogger 自己并没有做任何事情。因此,由应用程序的各个部分(包括框架和自定义代码)来记录他们想要记录的内容。
  • 当然,除非在尝试记录条目时ILogger 发生错误。除此之外,我赞同 Chris Pratt 所说的话。
  • 从 asp.net-core 的角度来看,管道早期的中间件应该能够在上游冒泡时捕获所有未捕获的错误。
  • 我自己的观察是,Program.main日志的第一行。我相信一切都被抓住了,但如果我有一个明确的答案,我可以与 Rollbar 分享这个issue。 Rollbar 两次记录未捕获的异常,他们的开发人员做了以下我想验证的声明:“一般来说,任何代码库都不能保证捕获异常并通过 ILogger 报告它们。”
  • 这是以下两个主题Handle errors in ASP.NET CoreLogging in ASP.NET Core的组合

标签: asp.net-core


【解决方案1】:

没有。 ILogger 是一个接口。它什么也没做。相反,ILogger 的实现应该记录未捕获的异常。听起来 Rollbar 已经在记录您的日志,因此您应该继续使用它来记录未捕获的异常,或者切换到 NLog、Serilog 或 log4net 等其他库。

就个人而言,我发现某些库在不同情况下确实会丢失消息,因此测试您的日志库很重要。仅仅相信消息被正确写入是不够的。您可以编写单元测试以确保您的代码使用 Moq 正确记录异常。这是来自this article 的示例。

_loggerMock.Verify
(
    l => l.Log
    (
        //Check the severity level
        LogLevel.Error,
        //This may or may not be relevant to your scenario
        It.IsAny<EventId>(),
        //This is the magical Moq code that exposes internal log processing from the extension methods
        It.Is<It.IsAnyType>((state, t) =>
            //This confirms that the correct log message was sent to the logger. {OriginalFormat} should match the value passed to the logger
            //Note: messages should be retrieved from a service that will probably store the strings in a resource file
            CheckValue(state, LogTest.ErrorMessage, "{OriginalFormat}") &&
            //This confirms that an argument with a key of "recordId" was sent with the correct value
            //In Application Insights, this will turn up in Custom Dimensions
            CheckValue(state, recordId, nameof(recordId))
    ),
    //Confirm the exception type
    It.IsAny<NotImplementedException>(),
    //Accept any valid Func here. The Func is specified by the extension methods
    (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
    //Make sure the message was logged the correct number of times
    Times.Exactly(1)
);

但是,即使这样也不能保证 Rollbar 或其他记录器一定会将您的消息发送到日志位置。您只能通过观察记录器的输出来确认这一点。

您还应该查看ILogger 文档中的this section,其中解释了如何配置日志记录并可能过滤它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多