slf4j logging syntax

LOG.info("error = {}", errmsg);

Correct and best.

LOG.info("error = ", errmsg);

This is most likely wrong. Unless errmsg is an exception, it will never be logged.

LOG.info("error = " + errmsg);

This one is not performing as good as first. You'll run String concatenation every time you hit this line while in first case variable replacement occurs only if statement will actually be logged.

Some time ago I blogged about different logging syntaxes in slf4j.


This is the best (jcabi-log on top of SLF4J):

Logger.info(this, "error=%s", errmsg);

It's a short alternative to:

private static Logger LOG = Logger.getLogger(Foo.class);
LOG.info(String.format("error=%s", errmsg));

First, it's convenient to let one utility class to take care about loggers instantiation. Second, it's very convenient to use String.format() for text formatting, because you always see the whole string and can easily translate it.


An alteration of the first form is the best

log.info("error={}", errmsg);

As others have said, the second example has to be a mistake as there is no format token to insert errmsg into "error = ", unless errmsg is a Throwable and info level logging is enabled. Then the logger will print a stracktrace.

For many years I preferred the string concatenation, the third form. I found it easier to read months or years later when I go back to read the code.

However, as Tomasz Nurkiewicz answered, the first form LOG.info("error={}", errmsg); is the best. The reason, though, isn't that String.format() is faster than String concatenation. It isn't. See Is it better practice to use String.format over string Concatenation in Java?.

The reason the first form performs better is that if the info level logging is disabled, then the logging framework doesn't have to call errmsg.toString() and it doesn't have to execute String.format() at all. The only case where errmsg.toString() has no performance cost is if errmsg is a String.

I also would suggest no whitespace around the = as many log aggregators like Splunk will automatically index error=errmsg into a field and value pair. Also, if this truly is an error, then I would write it to the error() level, not info(). And most likely there is a Throwable exception somewhere before this code that should go into the Throwable parameter.

And, logger, while it is probably declared as final, is a mutable object, so, it should be in lower case. See Should a "static final Logger" be declared in UPPER-CASE?.

which means the answer really should be

log.info("error={}", errMsg, exception);

Tags:

Logging

Slf4J