How to Filter serilog with UseSerilogRequestLogging

498 views Asked by At

I'm using serilog and try to filter out HTTP Methods that are not POST, GET, PUT, and DELETE. for example filter out OPTIONS Method.

I also use UseSerilogRequestLogging and Serilog.Expressions.

Everything work fine, Serilog is great. But the filter does't work. Any idea why?

Here is my code:

Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory 
    loggerFactory)
{
    ...
    app.UseSerilogRequestLogging(opt => opt.EnrichDiagnosticContext = 
    LogHelper.EnrichFromRequest);
    ...
}

LogHelper.cs:

public static class LogHelper
    {
        public static async void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;
            diagnosticContext.Set("Protocol", request.Protocol);
        }
    }

and appsettings.json:

  "Serilog": {
    "Using": [ "Serilog.Expressions" ],
    "Enrich": [ "FromLogContext" ],
    "Filter": [
      {
        "Name": "ByExcluding",
        "Args": {
          "expression": "@Properties['Protocol'] like '%OPTIONS%'"
        }
      }
    ]
  },
1

There are 1 answers

0
hobwell On

A shot in the dark, but have you tried either of these formats instead?

"Args": {
      "expression": "Protocol like '%OPTIONS%'"
}

"Args": {
      "expression": "Contains(Protocol, 'OPTIONS') ci"
}