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


(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:

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());

(Nicolas Peru) #2


While I understand your point about the fact that there is a formatting difference between the expression with the toString call or not, I am unsure of a good case where you would NOT want the stacktrace to be displayed ?
I would keep the rule as is and let you mark issues as won’t fix in the peculiar case where you actually want something different.