Hi!
I’m using SonarQube Community Edition Version 8.5.1 and try to write a java rule for the example below:
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
public class CheckDebugAndTraceLevel
{
private static final Log LOG = LogFactory.getLog(CheckDebugAndTraceLevel.class);
void foo()
{
if(LOG.isDebugEnabled())
{
LOG.debug("some debug text..");
}
LOG.debug("some debug text.."); // Noncompliant {{ check LOG.debug with an if statement}}
if(LOG.isTraceEnabled())
{
LOG.trace("some debug text..");
}
LOG.trace("some text.."); // Noncompliant {{ check LOG.trace with an if statement}}
}
}
I tried to check each StatementTree by getting the first token.
package org.sonar.samples.java.checks;
import java.util.List;
import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.JavaFileScanner;
import org.sonar.plugins.java.api.JavaFileScannerContext;
import org.sonar.plugins.java.api.tree.BaseTreeVisitor;
import org.sonar.plugins.java.api.tree.MethodTree;
import org.sonar.plugins.java.api.tree.StatementTree;
import org.sonar.plugins.java.api.tree.VariableTree;
@Rule(key = "DebugTraceCheck",
name = "Checks if debug & trace of the logger is enabled",
priority = Priority.CRITICAL,
tags = {"bug"})
public class DebugAndTraceRule extends BaseTreeVisitor implements JavaFileScanner
{
private JavaFileScannerContext context;
private boolean logFlag = false;
@Override
public void visitMethod(MethodTree tree)
{
super.visitMethod(tree);
String logOption = "";
List<StatementTree> statements = tree.block().body();
for(StatementTree statement : statements)
{
logOption = statement.firstToken().text();
if(((logOption + ".debug").equals("LOG.debug") ||
(logOption + ".trace").equals("LOG.trace")) &&
logFlag)
{
context.reportIssue(this, tree, "debug/trace levels of your logger must be enabled!");
}
}
}
@Override
public void visitVariable(VariableTree tree)
{
super.visitVariable(tree);
if(tree.type().symbolType().toString().equals("Log")) {
logFlag = true;
}
}
@Override
public void scanFile(JavaFileScannerContext context) {
this.context = context;
scan(context.getTree());
}
}
But I always get an AssertionError after executing JUnit Test.
If someone could please help, I would really appreciate it!