nandini nandini - 2 years ago 112
Java Question

logger usage, is parameterization 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download