3

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?

Remko Popma
  • 35,130
  • 11
  • 92
  • 114
nandini
  • 428
  • 2
  • 9
  • 20
  • Why is it? I wan to know what happens when we parametrize. I don't seem to find the code for the parametrization one. Also, If for log4j logger.info allows only object and throwable. not multiple arguments. – nandini Apr 29 '16 at 06:16
  • Well, instead of using an ancient logging framework like `log4j`, use a better one (or preferably a logging facade like `SLF4J`). – Kayaman Apr 29 '16 at 06:22
  • Yeah.. I was editing someone else's code. They already had log4j. I will change it. Thanks. I knew parametrization is better, but didn't know the reason. Your answer explains that. Thanks @kayaman :) – nandini Apr 29 '16 at 06:29

2 Answers2

2

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • From a 2021 perspective the first alternative would have prevented Log4j from expanding user supplied lookups (cf. [CVE-2021-44228](https://nvd.nist.gov/vuln/detail/CVE-2021-44228)). – Piotr P. Karwasz Dec 13 '21 at 18:40
  • 1
    @PiotrP.Karwasz actually even the parameterized version is susceptible to that, which is what makes it so dangerous. – Kayaman Dec 13 '21 at 18:44
1

Parameterized messages avoid formatting the text until Log4j is certain that the message will be logged. This allows you to avoid surrounding the logger.debug(...) call with checks like if (logger.isDebugEnabled())... which gives cleaner code.

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

When you say "outdated" you must be talking about Log4j 1.x. As of 2014, Log4j 2 is the cutting edge open source logging framework. It takes some ideas from SLF4J, like parameterized log messages, but adds a plugin system so you can easily add custom appenders, custom layouts and custom lookups. Furthermore Log4j 2 has support for custom log levels, lambda expressions and the lock-free and very performant Async Loggers. To spice things up, from release 2.6 Log4j 2 is garbage-free.

Kayaman is probably talking about Log4j 1, which has been End of Life since August 2015.

Community
  • 1
  • 1
Remko Popma
  • 35,130
  • 11
  • 92
  • 114