Serilog 已成功记录日志,但自动记录 HTTP GET api 调用。如何抑制HTTP调用?
我在日志文件中有这样的条目:
2024-10-25 06:24:10.040 -04:00 [INF] HTTP GET / responded 200 in 6107.3816 ms
program.cs
:
builder.Host.UseSerilog((context, configuration) =>
{
var requestLoggingOptions = new RequestLoggingOptions();
configuration.ReadFrom.Configuration(context.Configuration);
});
appsettings.json
:
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning", //If the error starts with Microsoft, it needs to be a warning level
"Microsoft.AspNetCore": "Warning",
"System": "Warning" //If the error starts with System, it needs to be a warning level
"System.Net.Http.HttpClient": "Warning" //probably not necessary because of the line above
}
},
"WriteTo": [ ... suppressed ...
],
"Filter": [
{
"Name": "ByExcludingOnly",
"Args": {
"expression": "e.Request.Method == \"GET\"",
}
}
]
},
我尝试添加其他最低级别和过滤器,但仍然创建 HTTP
GET
记录。
在您的
Program.cs
或类似位置,您将接到电话 UseSerilogRequestLogging()
。解决此问题的一种方法是直接为 API 请求分配较低的日志记录级别:
app.UseSerilogRequestLogging(options =>
options.GetLevel = (HttpContext ctx, double elapsed, Exception? ex) =>
ex != null
? LogEventLevel.Error
: ctx.Request.Method == "GET"
? LogEventLevel.Debug
: ctx.Response.StatusCode > 499
? LogEventLevel.Error
: LogEventLevel.Information);
(Serilog.Expressions 是另一个不错的选择,正如上面评论者提到的。)