Why is IsEnabled part of the ILogger Interface?

Viewed 534

The ILogger interface has a required method of IsEnabled. I am struggling to understand the purpose of that method in the interface. (Important note: I am not wondering about an implementing class, just the interface.)

It does not seem to be called by .Net Core during normal logging.

This answer seems to indicate that it is there for the developer to use when deciding to log.

But that does not make sense. As the developer I can make any method I need in the class that implements the ILogger interface in order to decide if I want to log or not. If a class implementing the interface does not need to provide an IsEnabled, it does not make sense to force all implementors to make it.

What is the purpose of is IsEnabled in the ILogger Interface?

1 Answers

Some times it might be costly to compute some arguments that are passed. Hence, the caller can filter out the work as needed:

if (logger.IsEnabled(LogLevel.Debug))
{
     logger.LogDebug("The message: {value}", DoSomethingCostlyHere());
}

Another common pattern is to put more details, such as PII or other sensitive data, into debug messages that wouldn't be surfaced in production:

if (logger.IsEnabled(LogLevel.Debug))
{
     logger.LogDebug("'{username}' logged in", username);
}
else 
{
     logger.LogInformation("User logged in");
}

Other logging frameworks have this too: NLog, Serilog, log4net, etc.

Related