How does Log4j implement lazy argument evaluation?

Given the Java argument evaluation mechanism , how does Log4j implement a lazy evaluation when formatting a message with curly braces "to avoid the cost of constructing parameters" when the log is disabled?

eg.

logger.debug("Entry number: {} is {}", i, entry[i]); 
+8
java lazy-evaluation log4j
Aug 24 '15 at 13:47
source share
1 answer

I assume that Log4j means, that with curly braces they avoid constructing a line when it is not needed (for example, the level is not debugged):

FROM

 logger.debug("Entry number: " + i + " is " + String.valueOf(entry[i])); 

A string is always evaluated even when it is not registered.

from

 logger.debug("Entry number: {} is {}", i, entry[i]); 

Log4j can first check the log level and then decide if it is worth building a Message-String.

Log4j uses an inner class ( org.slf4j.helpers.MessageFormatter ) that replaces all {} arguments. You can see the source code in org.slf4j.impl.Log4jLoggerAdapter.debug(String, Object[])

+11
Aug 24 '15 at 14:02
source share



All Articles