I am trying to understand the purpose of IsEnabled method in ILogger interface. I would expect that method is automatically called every time something can be log, but method Log is called no mater what returned IsEnabled.
Should I check IsEnabled inside Log method?
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= this.level;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (this.IsEnabled(logLevel)) //it seams that this is required ????
{
string s = formatter(state, exception);
string formatted = s.Replace("\r\n", "\r\n ");
Console.WriteLine(string.Format("{0,-15} {1,-5} - {2}", logLevel, eventId, formatted));
}
}
Then what is the purpose and who(why) calls IsEnabled.
The ILoggerFactory is the factory interface for creating an appropriate ILogger type instance and also for adding the ILoggerProvider instance. The Logging API includes the built-in LoggerFactory class that implements the ILoggerFactory interface.
NET Core agent logs information to the logs folder within C:\ProgramData\Contrast\dotnet-core\ on Windows or /var/tmp/contrast/dotnet-core/ on Linux, by default. Notes: Depending on the setup of the Windows profile and folder view settings, the ProgramData folder may be hidden.
ILogger : This interface provides the Log() method, which can be used to write a log message. ILoggerProvider : Logging providers implement this interface to write the logs to a specific destination. For example, the Console ILoggerProvider writes the logs to the console.
ILogger offers provider-based functionality to write to the console, the debug window, the Windows Event Log, to Microsoft Azure Ap Services diagnostics and logs, as well as to the TraceSource and the EventSource.
IsEnabled
is especially important when you pass parameters.
Without IsEnabled
logger.LogDebug("My debug message with {payload}", Serialize(myPayload));
In this case, myPayload is serialized on EVERY call to LogDebug
regardless of your log level settings. This could be an unnecessary hit in a production environment, and potentially lead to unexpected errors. What if Serialize method fails due to unexpected data?
With IsEnabled
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("My debug message with {payload}", Serialize(myPayload));
}
In this case, myPayload is only serialized when LogDebug
is enabled in your settings.
Balanced approach
Personally, I skip IsEnabled
checks with "constant text" calls to Log() methods (e.g., logger.LogDebug("constant string")
), and only test IsEnabled
when I need to log with parameters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With