asp.net-core - 如何使用 Serilog 抑制 'An unhandled exception has occurred while executing the request.' 日志消息

标签 asp.net-core exception logging .net-core serilog

当使用 app.UseExceptionHandler 实现我自己的异常处理程序时使用异常处理程序 lambda/delegate ( Documentation ) 我不想要微软的 Exception handler middleware记录此错误:

An unhandled exception has occurred while executing the request.


此异常消息使我的日志文件变得困惑,因为我自己负责使用适当的 LogLevel 记录异常。
这就是我注册自己的ErrorHandler的方式:
app.UseExceptionHandler(errorApp =>
                errorApp.Run(ErrorHandler));
this issue 中所述以简单的方式过滤这个确切的消息是不可能的。
如何过滤这个确切的日志消息,而不是来自中间件的其他内容?
我在用:
  • ASP.NET 核心 3.1
  • Serilog 3.4.0
  • 最佳答案

    如上述问题所述,我们可以使用 Filter expression为了这。不幸的是,该问题仅描述了已弃用包的解决方案,并且正在过滤来自中间件的所有消息,而不仅仅是提到的消息。

  • 安装 Serilog.Expressions
  • 更新匹配 appsettings.json使用此配置:
  •   "Serilog": {
        "Using": [ "Serilog.Expressions" ],
        "Filter": [
          {
            "Name": "ByExcluding",
            "Args": {
              "expression": "@l='Error' and SourceContext='Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware' and @mt='An unhandled exception has occurred while executing the request.'"
            }
          }
        ]
      }
    
  • 确保您有匹配的代码从 appsettings.json 加载配置as documented ,例如:
  • Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration)
                    .CreateLogger();
    
    这样您就可以保留来自 ExceptionHandlerMiddleware 的所有其他消息。并禁用冗余错误日志消息。
    旁注 :如果响应已经开始,我们的自定义异常处理程序将不会被执行——但会记录一个警告,异常将被重新抛出,稍后由另一个应用程序层记录——至少在我测试的应用程序中是这样。您可以通过在抛出异常之前的某处添加此代码来测试此行为(context 是当前的 HttpContext):
     await context.Response.WriteAsync("fish");
    

    关于asp.net-core - 如何使用 Serilog 抑制 'An unhandled exception has occurred while executing the request.' 日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66248055/

    相关文章:

    c# - 构造函数中的 HttpContext null

    asp.net-core - 失败 : Microsoft. AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]

    c# - ASP.NET MVC Core 应用程序中的实时通知

    exception - phpunit ExpectException() 错误的异常名称

    java - 在 Google Chrome 中工作的 URL 无法通过 Java w/Jsoup 访问?

    java - 在 junit 测试期间禁用记录器?

    c# - Request.HttpContext.Connection.ClientCertificate 始终为 null

    c# - System.Threading.Tasks.TaskExceptionHolder.Finalize() 处的 System.AggregateException

    java - 使用 java.util.logging 和 reSTLet 记录文件

    ios - 是否有使用 crashlytics 从 ios 发送非致命崩溃的解决方案?