ASP.NET Core 8 - exclude HTTP request body from logging for certain paths

111 Views Asked by At

Similar question like this: I'm using HttpRequestLogging like this:

builder.Services.AddHttpLogging(loggingOptions =>
{
    loggingOptions.LoggingFields = HttpLoggingFields.Request | HttpLoggingFields.Response;
}

However, for certain request paths, I would like to change the logging fields to not include logging the body, basically switch to

LoggingFields = HttpLoggingFields.RequestProperties | HttpLoggingFields.ResponsePropertiesAndHeaders;

if the request path contains /myspecial/request/notToLog

Is that possible?

1

There are 1 best solutions below

1
Guru Stron On BEST ANSWER

There are at least 3 ways which can help you to achieve that (based on actual case/setup):

  1. Use endpoint-specific configuration via attributes (if you want to customize specific endpoints), works both for controllers and minimal APIs endpoints:

    app.MapGet("/log-only-duration", [HttpLogging(HttpLoggingFields.Duration)]() => "will not be logged");
    
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
         [HttpGet()]
         [HttpLogging(loggingFields: HttpLoggingFields.Duration)]
         public string Get() => "will not be logged";
    }
    
  2. Use IHttpLoggingInterceptor:

    builder.Services.AddHttpLoggingInterceptor<CustomHttpLoggingInterceptor>();
    
    class CustomHttpLoggingInterceptor : IHttpLoggingInterceptor
    {
        public ValueTask OnRequestAsync(HttpLoggingInterceptorContext logContext)
        {
            // some predicate when to disable
            if (logContext.HttpContext.Request.Path.Value.Contains("toDisable", StringComparison.InvariantCultureIgnoreCase))
            {
                logContext.TryDisable(HttpLoggingFields.Request | HttpLoggingFields.Response);
            }
    
            return ValueTask.CompletedTask;
        }
    
        public ValueTask OnResponseAsync(HttpLoggingInterceptorContext logContext) => ValueTask.CompletedTask;
    }
    
  3. In some cases it can be appropriate to conditionally enable the logging with middleware branching (effectively disabling it for the rest):

    // some predicate when to enable logging
    app.UseWhen(ctx => !ctx.Request.Path.Value.Contains("toDisable", StringComparison.InvariantCultureIgnoreCase),
       aB => aB.UseHttpLogging());