How to check current log level using ILogger?

2.7k Views Asked by At

I am using Microsoft.Extensions.Logging.ILogger. I want to log request object only when LogLevel is set to Information

I know I can log the request object as

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

I am using Serilog as logger. This serializes the object and logs request as json string as expected. But I don't know if Logging framework checks the log level first and then serializes or always serializes first and then check for log level. Because I don't want to serialize the object on every call if LogLevel is set to higher than Information.

Is there anyway to check LogLevel using Microsoft.Extensions.Logging.ILogger

    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));
        }           
    }
1

There are 1 best solutions below

0
On

You should be able to use the IsEnabled method of ILogger<T>

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

Another alternative is to use a LoggingLevelSwitch to control the minimum level and make it accessible to your code, so that you can perform the check at a later time.

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));
    }           
}

You can also use multiple LoggingLevelSwitch instances for individual sinks (usually an argument called restrictedToMinimumLevel). See Serilog, Change the loglevel at runtime for a specific namespace (> MinimumLevel).