评估已配置的logproviders的LogLevel

时间:2018-04-10 06:13:06

标签: c# logging asp.net-core-2.0

我需要在asp.net core 2.0 Web应用程序中记录请求/响应。为此,我们创建了一个RequestLoggingMiddleware(见下文)。

此解决方案的缺点是每个请求都会读取正文流。有没有办法评估是否有为特定日志级别配置的logprovider。例如,在没有logprovider正在侦听DebugLog-Level的情况下,我们不需要读取正文流。

public class RequestLoggingMiddleware
{
    public ILogger<RequestLoggingMiddleware> Logger { get; }
    public RequestDelegate NextMiddleware { get; }


    public RequestLoggingMiddleware(RequestDelegate nextMiddleware, ILogger<RequestLoggingMiddleware> logger)
    {
        NextMiddleware = nextMiddleware;
        Logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        using (MemoryStream loggableResponseStream = new MemoryStream())
        {
            Logger.LogDebug(await FormatRequest(context.Request));

            await NextMiddleware(context);
        }
    }

    private static async Task<string> FormatRequest(HttpRequest request)
    {
        Stream body = request.Body;
        request.EnableRewind();
        byte[] buffer = new byte[Convert.ToInt32(request.ContentLength)];
        await request.Body.ReadAsync(buffer, 0, buffer.Length);
        string bodyAsText = Encoding.UTF8.GetString(buffer);
        request.Body = body;

        var messageObjToLog = new
        {
            scheme = request.Scheme,
            host = request.Host,
            path = request.Path,
            queryString = request.Query,
            requestBody = bodyAsText
        };

        return JsonConvert.SerializeObject(messageObjToLog);
    }

}

1 个答案:

答案 0 :(得分:1)

ILogger接口将IsEnabled方法定义为:

bool IsEnabled(LogLevel logLevel);
  

有没有办法评估是否有logprovider   为特定的日志级别配置。

ILogger的默认实现保留了已配置记录器的集合。 IsEnabled方法的实现完全按照您的描述工作:如果至少有一个记录器指定了日志级别,则枚举所有记录器并返回true

Logger Source code on github

因此,以下检查应该为您完成工作:

if (logger.IsEnabled(LogLevel.Debug))
{
    //  ...
}