Formatting floating point numbers in SLF4J

Matthias Braun picture Matthias Braun · Mar 28, 2014 · Viewed 14.6k times · Source

I'd like to format my doubles and floats to a certain number of decimal places with SLF4J.

Basically, I'm looking for the equivalent of Java's String.format("%.2f", floatValue) in SLF4J.

Having read through SLF4J's documentation and googling around I couldn't find a hint whether it has that feature.

I'm using slf4j-api:1.7.6 and slf4j-jdk14:1.7.6

Any help is much appreciated.

Answer

Isaac picture Isaac · May 25, 2014

I am assuming that you're referring to SLF4J's convention of expanding parameters, e.g.:

float f;
...
logger.debug("My number is {}", f);

So, the answer is no. As of SLF4J 1.7.7, what you're asking to do is impossible as SLF4J's expansion algorithm doesn't allow for custom renderers (such as the one available via Log4J).

Seems worthy of a feature request, though.

EDIT:

Well, {} is "only supported" for performance considerations, current formatting implementation outperforms String.format() at 10 times. http://www.slf4j.org/faq.html#logging_performance so it's unlikely to change

(source)