Sonar violation: Invoke method(s) only conditionally

Viewed 10770

Our company just started a sonar farm. I was curious about our code quality and wanted to improve.

I have a code containing such logger calls:

LOGGER.error(String.format("Cannot load object in status %s (%s)", status, statusDescription), e);

LOGGER.info(String.format("%s object(s) loaded in status %s (%s)", objects.size(), status, statusDescription));

Sonar triggers rule squid:S262, Invoke method(s) only conditionally "Preconditions" and logging arguments should not require evaluation. Rule triggered by both theses lines.

About this one, I'm not really sure to understand what's going on. The explanation seams not well fitting to my use case. Sonar doc provided this example:

logger.log(Level.DEBUG, "Something went wrong: " + message);  // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages

which I perfectly understand (debug will not be logged in production, thus unnecessary operations will occurs). But for info and error level, I would assume that you want to log it anyway. Moreover, in my case, I want both to be logged.

Which is the good approach ? Rewrite differently not using String.format ? Tune sonar to not fire on info/error level ? Just ignore sonar on this one ? Something else ?

1 Answers
Related