当使用 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 中所述以简单的方式过滤这个确切的消息是不可能的。如何过滤这个确切的日志消息,而不是来自中间件的其他内容?
我在用:
最佳答案
如上述问题所述,我们可以使用 Filter expression为了这。不幸的是,该问题仅描述了已弃用包的解决方案,并且正在过滤来自中间件的所有消息,而不仅仅是提到的消息。
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/