nandini nandini - 9 months ago 49
Java Question

logger usage, Is parametrization better or using + to add arguments?

Which of the following is a better usage of logger?

  1. Parametrize (log4j 2)"User {} has logged in using id {}", map.get("Name"), user.getId());

  2. Using + operator (log4j)"User"+ map.get("Name") +" has logged in using id " +user.getId());

And why?


Even if there were nothing else, the additional StringBuilder shenanigans that happen when using + would make using parameters the obvious choice.

Not to mention that when concatenating the values, the toString() method of all the parameters will be called even if the logging level isn't enabled, meaning that you're wasting CPU to build a String that will never be logged. This would have an (albeit minor) effect if there are lots of debug() statements, when DEBUG level is usually disabled in production environments.

This answer is based on modern logging frameworks, not outdated ones like Log4J.