Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin best way to log using slf4j

I have an spring boot project with default log configuration using logback. I have always used this approach for logging purpose inside my applications:

logger.info("Get user paginated: filter {}",user)

Now i am learning Kotlin and I was reading about String templates.If i rewrite my sentence using $ would be:

logger.info("Get user paginated: filter $user")

Which would be the better way to log in Kotlin with Spring boot?

like image 550
CRISTIAN ROMERO MATESANZ Avatar asked Aug 30 '19 13:08

CRISTIAN ROMERO MATESANZ


Video Answer


2 Answers

The better way is neither; add https://github.com/MicroUtils/kotlin-logging and write

logger.info { "Get user paginated: filter $user" }

with the advantages of both.

like image 65
Alexey Romanov Avatar answered Oct 19 '22 07:10

Alexey Romanov


The point of the {} syntax supported by SLF4J is to avoid useless String concatenation and toString() calls if the log message is never actually generated (for example because the level is higher than info.

A template string doesn't avoid that: the user.toString() method needs to be called, and its result needs to be appended to the static part of the log message, before being passed to logger.info().

So, if you're looking for the best performance, use SL4J parameters. If you don't care and find the template string more readable, use the template string.

like image 9
JB Nizet Avatar answered Oct 19 '22 08:10

JB Nizet