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));
}
}
You should be able to use the
IsEnabled
method ofILogger<T>
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.You can also use multiple
LoggingLevelSwitch
instances for individual sinks (usually an argument calledrestrictedToMinimumLevel
). See Serilog, Change the loglevel at runtime for a specific namespace (> MinimumLevel).