Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call IsDebugEnabled in log4net?

Tags:

c#

log4net

I'm curious as to why I see people write log4net logging code like the following:

if (_logger.IsDebugEnabled)
{
    _logger.Debug("Some debug text");
}

I've gone through the disassembly for log4net, and calling Debug makes another call to the same code to see if it's enabled before actually logging, so the IsDebugEnabled call is unnecessary and actually is duplicated code.

Is there a reason people do this? Maybe an old pattern that used to be necessary in older versions but isn't anymore? Or could there be a legitimate reason for it? Or maybe people just don't know that they don't need to do it?

This same behavior is there for the other levels (Info, Error, Warn, Finest, etc.) as well.

like image 729
Joe Enos Avatar asked Dec 07 '10 23:12

Joe Enos


People also ask

Is logger Isdebugenabled necessary?

It's useful when the String your passing to logger. debug(...) takes time to evaluate, in that case you can skip this evaluation if debug is not enabled. IMO this makes the code a lot less readable so it should only be used when there's a significant performance improvement.

What is the purpose of log4net?

log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary.

Is log4j available in c#?

log4j is a popular logging package written in Java. log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.


2 Answers

This pattern is used purely for performance reasons, specifically when logging to a certain logging level will be skipped because the logging level is not currently enabled. It is a lot cheaper to check the boolean IsDebugEnabled flag and skip the method call than it is to call the Debug method with arguments and the method to return without logging.

If you were to call the Debug method and pass in a message containing something that was costly to create, you could skip the creation of the message altogether by first checking the enabled flag.

All that being said, unless you are making log messages that are very expensive to make (eg. something like a stack trace) or you are logging in a tight loop, it is unlikely that it will be a bottleneck for your code.

like image 79
adrianbanks Avatar answered Sep 19 '22 06:09

adrianbanks


The message could be expensive to build. Wrapping it in the if statement ensures it is only created when necessary.

Another pattern that addresses this issue is:

_logger.Debug(() => "Some expensive text");

I don't know if log4net supports anything like that, though.

like image 32
Bryan Watts Avatar answered Sep 17 '22 06:09

Bryan Watts