Java rule for redundant log actions

Redundant log actions

When writing to log, avoid redundant methods invocations which will have no effect when content is not written to log anyway due to the log level.
Both example lines below causing redundant toString() invocations.

** Noncompliant Code Example**

log.debug("Current object: {}", object.toString());
log.debug("Current object: " + object);

** Compliant Solution**

log.debug("Current object: {}", object);

This can be a Code Smell rule which affects performance.

Hello @liran, thanks for the suggestion.

We already have S2629 doing something similar, does it cover your use-case?

Hi @Quentin
I executed SonarQube and SonarLint on below code lines, and I don’t this rule, or any other rule catching them. These are common logging issues - especially since commonly used with Lombok SLF4J annotation as ‘log’ is the default logger variable name.

I checked - it is not catching them when logger used with Lombok @Slf4j annotation
when called the default ‘log’ name, or any other name.
Then is it possible to update this rule to catch also logger variables coming from @Slf4j annotation ?

log.debug("Current object: {}", object.toString());
log.debug("Current object: " + object);

Thanks for the clarification, it makes sense now. To sum up:
we are supporting the cases where the logger is explicitly declared:

public static final org.slf4j.Logger log = LoggerFactory.getLogger(LogExample.class);

log.debug("Current object: {}", object.toString()); // issue: S2629
log.debug("Current object: " + object); // issue: S2629

But not when Lombok annotations are used:

class LogExample {
  // Annotation "@Slf4j" will generate: 
  //private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);

  log.debug("Current object: {}", object.toString()); // No issues
  log.debug("Current object: " + object); // No issues

As a general observation, I think you can guess that tools modifying source code (such as Lombok) are not working well with static analysis tools (relying only on source code).

In the implementation of the rule, we are not simply relying on variable names, we also use types to improve the relevance of our results. When the declaration of the variable is not in the source code, we are can not say anything. In order to support this situation, we basically have to re-implement the @Log logic on our side. As it is not trivial at all, this seems way out of the scope for now.

Hope it clarifies the situation.