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

Exclude specific endpoint serilog logging using aspnet core

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

希望这对其他人有所帮助!