Log debug enabled check in java

What is the point of having an if statement here? The severity level can be changed in the log4j.xml configuration file. If the severity level is debugged, it will log a debug message, otherwise it will not.

What is the meaning of the if statement below?

if (log.isDebugEnabled()) { log.debug("I am logging something"); } 
+7
source share
3 answers

In your example, there is no need for an "if" expression (between "if" is not a loop)

But if you accept the example below, you will see that we are doing concatenation, and if the log level is information, then otherwise this concatenation operation will be performed. To improve performance, we test this condition.

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

Additional Information:

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

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

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

Example:

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

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

My opinion is that when there is a simple line in your example, if there is no need for logging, if there is something more complex (even more complicated, as in my example), this can save some CPU time in working mode (without debugging mode )

You should also understand that when in case of concatenation there is a call to String.valuOf() , which (for non-null objects) calls the toString() method, which can be a performance issue for large data objects (beans with many properties) if you consider that it does not use business logic (therefore, it is "useless").

+2
source

This is a performance optimization. This is to prevent arguments from being reached before log.debug . It is only worth doing if building a log message is especially expensive (for example, serializing an XML document).

This is described in detail in a brief introduction to log4j .

0
source

All Articles