Rafael Miceli
Rafael Miceli

Reputation: 2114

Exclude specific endpoint serilog logging using aspnet core

We have an aspnetcore application and we have a healthcheck that makes request to an endpoint every x seconds. Our API is using serilog, logging level information which log each request made to the API.

My question is: How can we filter to exclude from log requests made to a specific endpoint?

Just for example this is our logging code today:

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

Today we can only filter all requests. How do we filter a specific endpoint request?

Upvotes: 7

Views: 10214

Answers (2)

Bo Ngoh
Bo Ngoh

Reputation: 163

I had a very similar situation (don't want to be logging all Health queries), and found the solution on the official documentation itself: https://github.com/serilog/serilog-expressions

It's like your result, although yours didn't work for me; but their solution is entirely defined by a string so no idea how I would tweak it as a power user, but it worked just fine for my purposes.

The specific piece of code is this:

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

Upvotes: 0

Rafael Miceli
Rafael Miceli

Reputation: 2114

I found the way to do this.

Instead of Exclude by MessageTemplate, I excluded by Property Value.

The filter is like this:

Filter.ByExcluding(c => c.Properties.Any(p => p.Value.ToString().Contains("swagger")))

In the end the code should look like this:

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

Hope this helps someone as helped me!

Upvotes: 22

Related Questions