我们有一个 aspnetcore 应用程序,并且有一个健康检查,每 x 秒向端点发出一次请求。我们的 API 使用 serilog,记录对 API 发出的每个请求的日志级别信息。
我的问题是:我们如何过滤以排除对特定端点发出的日志请求?
举个例子,这是我们今天的日志代码:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.Enrich.FromLogContext()
.Filter.ByExcluding(c => c.MessageTemplate.Text.Contains("Request"))
.WriteTo.Console()
.WriteTo.RollingFile(hostingContext.Configuration["log-path"]))
.Build();
今天我们只能过滤所有请求。我们如何过滤特定端点请求?
我找到了做到这一点的方法。
我没有按
MessageTemplate
排除,而是按属性值排除。
滤镜是这样的:
Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("swagger")))
最后代码应该是这样的:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.Enrich.FromLogContext()
.Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("swagger")))
.WriteTo.Console()
.WriteTo.RollingFile(hostingContext.Configuration["log-path"]))
.Build();
希望这可以帮助别人,就像帮助我一样!
我遇到了非常相似的情况(不想记录所有健康查询),并在官方文档本身上找到了解决方案: https://github.com/serilog/serilog-expressions
就像你的结果,虽然你的结果对我不起作用;但他们的解决方案完全由字符串定义,因此不知道作为高级用户如何调整它,但它对于我的目的来说工作得很好。
具体的一段代码是这样的:
.Filter.ByExcluding("RequestPath like '%/health%'")