使用 aspnet core 排除特定端点 serilog 日志记录

问题描述 投票:0回答:2

我们有一个 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();

今天我们只能过滤所有请求。我们如何过滤特定端点请求?

asp.net-core .net-core serilog
2个回答
22
投票

我找到了做到这一点的方法。

我没有按

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();

希望这可以帮助别人,就像帮助我一样!


0
投票

我遇到了非常相似的情况(不想记录所有健康查询),并在官方文档本身上找到了解决方案: https://github.com/serilog/serilog-expressions

就像你的结果,虽然你的结果对我不起作用;但他们的解决方案完全由字符串定义,因此不知道作为高级用户如何调整它,但它对于我的目的来说工作得很好。

具体的一段代码是这样的:

.Filter.ByExcluding("RequestPath like '%/health%'")

© www.soinside.com 2019 - 2024. All rights reserved.