False positive with SLF4J logging and Throwable toString(): No need to call "toString()" method as formatting and string conversion is done by the Formatter

java

(Tim Bartley) #1

The part of the Java “Printf-style format strings should be used correctly” rule that complains when a parameter is passed to a format string with it’s toString method being called generates false positives when SLF4J format strings are passed Throwable’s calling their toString method.

When these objects are passed without calling the toString method they are formatted a different way. They do not require a format parameter and the etnire stack trace of the throwable is logged.

To suppress this behaviour it is desirable to be able to explicitly pass t.toString() as a parameter to the format string.

This aspect of the rule is in general good but not in this instance. So it’s undeseriable to

a) Deactivate the rule as a whole
b) Deactive even the bit that complains about .toString calls (if that were even possible)
c) Annotate every instance of this throughout sourcecode with //NOSONAR since it’s still desirable to have such statements analysed for other issues.

SonarQube CE version: 7.3.0.15553

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FormatterFalsePositive {
    private static final Logger log = LoggerFactory.getLogger(FormatterFalsePositive.class);

    public static void main() {
        Exception e = new Exception("An exception");
        log.error("Exception: {}", e.toString());
    }
}