Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use an extra if condition for logger.debug()? [duplicate]

Tags:

java

log4j

Possible Duplicate:
In log4j, does checking isDebugEnabled before logging improve performance?

I have seen people using log4j in the manner below:

if(logger.isDebugEnabled())
{
    logger.debug(" message ");
}

However, I checked the documentation for the logger.debug API and found that it checks if debug is enabled before logging the message. In that case, what is the point of writing extra the if?

Wouldn't it be exactly the same to just write

logger.debug(" message ");

?

like image 432
rbhawsar Avatar asked Nov 07 '12 10:11

rbhawsar


People also ask

What is extra debug logging?

Debug logs are logs with an extended logging level. They can be helpful to support engineers when the application logs are insufficient to investigate an issue. Debug logs can be enabled for both Backup Manager and Recovery Console.

When would you use a debug logger?

If you want to print the value of a variable at any given point, you might call Logger. debug . This combination of a configurable logging level and logging statements within your program allow you full control over how your application will log its activity.

What does logger debug do in Python?

Debugging is an important step of any software development project. The logging module is part of the standard Python library, provides tracking for events that occur while software runs, and can output these events to a separate log file to allow you to keep track of what occurs while your code runs.

Does debug logging affect performance?

Log levels can be set for various parts of the system. In normal operation the log level for all of the subsystems should be set to INFO. DEBUG level can adversely impact performance.


2 Answers

If you're really just writing

logger.debug(" message ");

then there's no benefit. But consider:

logger.debug("This: " + message + " happened on thread " + thread +
            "because " + cause);

You don't want that string concatenation (and more expensive conversions, potentially - think about things that you might want to log, but which are costly to convert to strings) to be executed if the result is just going to be thrown away.

If logging has a significant performance impact in the normal case, that's a disincentive to add logging code which could really help you in situations where suddenly you want to turn diagnostics on.

like image 94
Jon Skeet Avatar answered Oct 21 '22 12:10

Jon Skeet


I think the idea here is to prevent any parameter evaluation - in your case it's simple, but for example let's say it was more like:

logger.debug("Foo" + bar() + " bar: " + foo());

Okay this is contrived, but if debug is not enabled, you may not want to execute bar() and foo() and the string concatenation...

like image 42
Nim Avatar answered Oct 21 '22 11:10

Nim