user2434
user2434

Reputation: 6399

log debug enabled check in java

What is the point of having the if statement here? The severity level can be changed in log4j.xml config file. If the severity level is debug, it'll log the debug message, else it will not.

What is the significance of the if statement below?

   if (log.isDebugEnabled())
    {
        log.debug("I am logging something");
    }

Upvotes: 19

Views: 26340

Answers (3)

Sridhar G
Sridhar G

Reputation: 818

In your example there is no need for an 'if' statement

But if you take the below example then you can see that we do a concatenation and if the log level is info then unneccesarily this concatenation operation will be done. For better performance we check this condition.

if (log.isDebugEnabled())
{
    log.debug("I am logging " + 1234 + ".");
}

Extra info:

Use slf4j to avoid such if conditions. The above statement can be rewritten in slf4j as follows,

log.debug("I am logging {} .", 1234);

Upvotes: 31

Betlista
Betlista

Reputation: 10549

This is considered as good practice. For example if there is some string concatenation it's not evaluated and checked in log4j, but it is checked first.

Example:

if ( log.isDebugEnabled() ) {
    log.debug( "N=" + N + ", a=" + Arrays.toString( a ) );
}

method Arrays.toString() and also concatenation is not performed if debug is not enabled. If there is no if it is invoked first and checked later, that's all ;-)

My opinion is that when there is simple String as in your example the if around the logging is not needed, if there is something more complicated (even more complicated as in my example) this can save some CPU time in production mode (without debug mode enabled).

You have to realize also that when in case of concatenation there is String.valuOf() call which (for not null objects) calls toString() method, which can be really performance issue for big data objects (beans with many properties) if you consider that it's invoking no business logic (therefore it is "useless").

Upvotes: 3

harto
harto

Reputation: 90483

It's a performance optimisation. It's done to avoid evaluating the arguments to log.debug. It's only worth doing if constructing the log message is particularly expensive (e.g. serialising an XML document).

This is covered in some detail in the Short introduction to log4j.

Upvotes: 4

Related Questions