【问题标题】:How to check current log level using ILogger?如何使用 ILogger 检查当前日志级别?
【发布时间】:2021-10-18 16:07:34
【问题描述】:

我正在使用Microsoft.Extensions.Logging.ILogger。我只想在 LogLevel 设置为 Information 时记录请求对象

我知道我可以将请求对象记录为

_logger.LogInformation("{request}", request);

我使用Serilog 作为记录器。这会按预期将对象和日志请求序列化为 json 字符串。但是我不知道 Logging 框架是先检查日志级别然后序列化还是总是先序列化然后检查日志级别。因为如果 LogLevel 设置为高于 Information,我不想在每次调用时序列化对象。

有没有办法使用Microsoft.Extensions.Logging.ILogger检查LogLevel

    private Microsoft.Extensions.Logging.ILogger<RoutesController> _logger = null;

    public RoutesController(Microsoft.Extensions.Logging.ILogger<RoutesController> logger)
    {            
        _logger = logger;
    }
    
    public void Route([FromBody]JObject request)
    {
       //how to check current LogLevel here?
        if(_logger.LogLevel == "Information")
        {
            _logger.LogInformation(JsonConvert.Serialize(request));
        }           
    }

【问题讨论】:

    标签: asp.net-core serilog coreclr microsoft.extensions.logging


    【解决方案1】:

    你应该可以使用ILogger&lt;T&gt;IsEnabled方法

    if (_logger.IsEnabled(LogLevel.Information)
    {
        //... 
    }
    

    另一种选择是使用LoggingLevelSwitch 来控制最低级别并使其可供您的代码访问,以便您稍后执行检查。

    var log = new LoggerConfiguration()
      .MinimumLevel.ControlledBy(LoggingLevelSwitches.GlobalLevelSwitch)
      .WriteTo.Console()
      .CreateLogger();
    
    public class LoggingLevelSwitches
    {
        public static readonly LoggingLevelSwitch GlobalLevelSwitch
            = new LoggingLevelSwitch(LogEventLevel.Information);
    }
    
    public void Route([FromBody]JObject request)
    {
        // (example... You prob. would check for >= Information)
        if (LoggingLevelSwitches.GlobalLevelSwitch.MinimumLevel == LogEventLevel.Information)
        {
            _logger.LogInformation(JsonConvert.Serialize(request));
        }           
    }
    

    您还可以为单个接收器使用多个LoggingLevelSwitch 实例(通常是一个名为restrictedToMinimumLevel 的参数)。见Serilog, Change the loglevel at runtime for a specific namespace (> MinimumLevel)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 2013-12-22
      • 2021-12-29
      • 2011-08-14
      • 1970-01-01
      相关资源
      最近更新 更多