2

I have this piece of code:

String cause = ExceptionUtils.getStackTrace(result.getThrowable());
result.setAttribute(EXCEPTION, cause);
LOGGER.error(MessageFormat.format("Test has failed: {0}", cause));
collect(result);

I am using SLF4J for logging

However SonarLint keep warning me about:

"Preconditions" and logging arguments should not require evaluation

in my logging. According to the description of the issue:

Passing message arguments that require further evaluation into a Guava com.google.common.base.Preconditions check can result in a performance penalty. That’s because whether or not they’re needed, each argument must be resolved before the method is actually called. Similarly, passing concatenated strings into a logging method can also incur a needless performance hit because the concatenation will be performed every time the method is called, whether or not the log level is low enough to show the message. Instead, you should structure your code to pass static or pre-computed values into Preconditions conditions check and logging calls. Specifically, the built-in string formatting should be used instead of string concatenation, and if the message is the result of a method call, then Preconditions should be skipped altogether, and the relevant exception should be conditionally thrown instead.

I am using built-in message formatting, however as you can see my argument is dynamic, as it is calculated from result. How to satisfy the sonar for this issue? This code gets invoked when error is thrown, so the cause is never null and is calculated before passing to the logging.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Johnyb
  • 980
  • 1
  • 12
  • 27
  • Does this answer your question? [Built-in string formatting vs string concatenation as logging parameter](https://stackoverflow.com/questions/42388341/built-in-string-formatting-vs-string-concatenation-as-logging-parameter) – Progman Aug 25 '21 at 17:59

1 Answers1

3

It's not clear ( to me at least ), what logging framework you are using, but I think you can make this Sonar problem go away be checking to see if the logger is enabled for the the ERROR level. Something like

if (LOGGER.isEnabled(Level.ERROR) { 
    LOGGER.error(MessageFormat.format("Test has failed: {0}", cause));
}

You'd need to check your logging framework syntax though.

If you are using slf4j you can try using this syntax

LOGGER.error("Test has failed: {}", cause)

DaveH
  • 7,187
  • 5
  • 32
  • 53