Log4j2 using {} against using %d or %s

Andy897 picture Andy897 · Jan 8, 2017 · Viewed 11.5k times · Source

In Log4j2, are both the following equally efficient and do not cause any string concatenation with a log level more specific than DEBUG ? And for any reason/situation will one be preferred over other ?

log.warn(String.format("Number of cars : %d",carCount));
log.warn("Number of cars : {}",carCount );

And does {} works with any type of Object ?

Answer

Remko Popma picture Remko Popma · Jan 8, 2017

The {} notation is much more efficient than the %s %d String format notation. (There are benchmarks for this, I'll add some numbers later.)

The {} notation accepts any Object or primitive value, where the %s %d ... String format requires that the type of the parameter matches the format or an exception is thrown. So generally, {} is more convenient.

There are cases where you want to use the String format syntax, since it gives you very fine-grained control over the formatting. If you want to "pretty-print" a large number as 1,234,567.123, or control the number of digits behind the decimal point, then {} is not enough.

Log4j2 allows you to mix both usages. It is possible to use the String format syntax everywhere (by using LogManager.getFormattedLogger), but perhaps more convenient is to use the default {} format most of the time, and only use the String format syntax when you need the fine grained control with the printf method:

logger.printf(Level.INFO, "Logging in user %1$s with birthday %2$tm %2$te,%2$tY", user.getName(), user.getBirthdayCalendar());

Internally, with the {} format Log4j2 makes an effort to avoid creating Strings or other temporary objects. This is not possible with the String format syntax.