0

I have the below two patterns that i am thinking for logging. I need your help on understanding indeep of this two differences. Here my intention is append and concatination.

log.info("Name: " +name);

log.info("Name: {}", name);

Can anyone please help on understanding this completely. Also, please suggest if any better approach as per current market.

Thanks, Nagendra.

Nagendra
  • 17
  • 2
  • https://www.slf4j.org/faq.html#logging_performance – JEY May 23 '18 at 11:36
  • It doesn't particularly matter in this case. When you have 2 or more placeholders, the second style becomes the most readable in my opinion. Performance is a nice bonus, but I wouldn't stress over it. – Michael May 23 '18 at 11:36
  • @Michael sure but in case of logging you want to avoid performance issue on what your are doing. – JEY May 23 '18 at 11:41

2 Answers2

4

It is not only a matter of readability, it is also a matter of performance.

This option:

log.info("Name: {}", name);

Will perform better than this one:

log.info("Name: " +name);

That is because the second method will cause the JVM to execute a String concatenation, even if the log will not be printed.

The first option is easier to read when you wish to print many things.

The first option is easier to maintain and refactor, as you can quickly adjust the text and location of parameter without going into concatenation hell.

Guilherme Mussi
  • 956
  • 7
  • 14
0

First of all, you have to be aware that:

"Name: " + name

Will always concatenate Strings and create new objects.

However the second approach is better since it is making String interpolation (Inserting values instead of brackets) only when correct level of logging is turned on and this concatenation is needed.

If you will have a lot of info logs with String concatenation and application logging level will be set to only errors the second approach will prevent from creating new String objects.

Tomasz Bawor
  • 1,447
  • 15
  • 40