I have often heard people saying that its one of the best practices to avoid String Concatenation
and use {}
instead while logging.
I was
Some of the answers to this question explain:
The short version is that format-based usage faster because in
Logger.debug("my name is {}", name);
the expensive string bashing only occurs after log4j decides that the event needs to be logged; e.g. after the filtering based on the logging level, etcetera.
By contrast, with the string concatenation version
Logger.debug("my name is " + name);
the string bashing happens while evaluating the arguments. Thus, it happens even in the cases where no event is actually logged. (You can partially avoid that with guards in your code, but it makes the logging code verbose.)
But take a look at this example:
log.debug("Count: " + list.size());
log.debug("Count: {}", list.size());
The format version will be faster, but both versions always evaluate the list.size()
expression. If that is an expensive operation, then you may need to resort to using a guard; e.g.
if (log.isDebugEnabled()) {
log.debug("Count: " + list.size());
}