Question

Here are a few ways to do logging. Using SLF4J:

What's a best/right way to do it?

log.debug(John + " has " + number +" apples with him");
log.debug("{} has {} apples with him", John, number);
log.debug(format("%s has %d apples with him", John, number));
Was it helpful?

Solution

The second option,

log.debug("{} has {} apples with him", John, number);

is the "right" way to do it.

Parameterized logging was introduced to avoid the expense of computing a formatted string when the message isn't even enabled. This requires that you pass the format specification and the necessary arguments to the logger. The logger only completes the formatting operation if it is enabled.

The other two options preemptively format the message, even if it won't be logged.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top