Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j v2 formatting capabilities

In case of loggers its said that for every logger there is hidden cost of parameter construction .

eg:-

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

This incurs the cost of constructing the message parameter, i.e. converting both integer i and entry[i] to a String, and concatenating intermediate strings, regardless of whether the message will be logged or not. This cost of parameter construction can be quite high and it depends on the size of the parameters involve.

On log 4j site its given that The best approach to avoid the cost of parameter construction is to use Log4j 2's formatting capabilities. For example, instead of the above write:

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

Whats happening inside this formatting capability that cost incurred this time will be less. Is it not creating strings like it used to create in previous cases. please someone explain this?

like image 380
Timothy Drisdelle Avatar asked Jan 26 '26 21:01

Timothy Drisdelle


1 Answers

In the first example, it is creating the String even if not needed. However, if it is needed this is likely to be the most efficient way. BTW The String.valueOf is redundant.

The second option is faster if the message is turned off. This avoid creating a String which is later discarded because it can check whether debugging is enabled before building the String. Note: if you do need the String, it is likely to be slower as it has to parse the message format.

The best of both worlds, but the wordest is

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

In this case, you do the check and if it is to be logged, get the fastest message generation.


There are logging frameworks which avoid creating any String and are fast enough you don't need to turn debugging off in the first place, but these are not simple to use, and I would avoid them unless you need more performance.

like image 111
Peter Lawrey Avatar answered Jan 29 '26 11:01

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!