Skip to content
Advertisement

logger usage, is parameterization better or using + to add arguments?

Which of the following is a better usage of logger?

  1. Parametrize (log4j 2)

    logger.info("User {} has logged in using id {}", map.get("Name"), user.getId());`
    
    
  2. Using + operator (log4j)

    logger.info("User"+ map.get("Name") +" has logged in using id " +user.getId());`
    
    

And why?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement