ASP.NET Core 8 - 从某些路径的日志记录中排除 HTTP 请求正文

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

类似的问题,如this:我正在使用

HttpRequestLogging
,如下所示:

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

但是,对于某些请求路径,我想更改日志记录字段以不包括记录正文,基本上切换到

LoggingFields = HttpLoggingFields.RequestProperties | HttpLoggingFields.ResponsePropertiesAndHeaders;

如果请求路径包含

/myspecial/request/notToLog

这可能吗?

c# asp.net-core httprequest .net-8.0
1个回答
0
投票

至少有 3 种方法可以帮助您实现这一目标(基于实际案例/设置):

  1. 通过属性使用特定于端点的配置(如果您想自定义特定端点),适用于控制器和最小 API 端点:

    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. 使用

    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. 在某些情况下,您可以使用中间件分支

    完全禁用日志记录
    // some predicate when to enable logging
    app.UseWhen(ctx => !ctx.Request.Path.Value.Contains("toDisable", StringComparison.InvariantCultureIgnoreCase),
       aB => aB.UseHttpLogging());
    
© www.soinside.com 2019 - 2024. All rights reserved.