Skip to content

Commit

Permalink
Update LoggersNamedForEnclosingClass to convert `LoggerFactory#getLog…
Browse files Browse the repository at this point in the history
…ger(..)` method parameters which are not J.FieldAccess instances. (fixes: #69)
  • Loading branch information
pway99 committed Aug 30, 2022
1 parent 1665961 commit 4923215
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Execu
}

String enclosingClazzName = firstEnclosingClass.getSimpleName() + ".class";
String argumentClazzName = ((J.FieldAccess) mi.getArguments().get(0)).toString();
if (enclosingClazzName.equals(argumentClazzName)) {
return mi;
if (mi.getArguments().get(0) instanceof J.FieldAccess) {
String argumentClazzName = ((J.FieldAccess) mi.getArguments().get(0)).toString();
if (enclosingClazzName.equals(argumentClazzName)) {
return mi;
}
}

return mi.withTemplate(JavaTemplate.builder(this::getCursor, "LoggerFactory.getLogger(#{})")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import org.openrewrite.Recipe
import org.openrewrite.java.JavaParser
import org.openrewrite.java.JavaRecipeTest

@Suppress("RedundantSlf4jDefinition")
class LoggersNamedForEnclosingClassTest : JavaRecipeTest {
override val parser: JavaParser
get() = JavaParser.fromJavaVersion().classpath("slf4j-api").build()
Expand Down Expand Up @@ -48,7 +49,27 @@ class LoggersNamedForEnclosingClassTest : JavaRecipeTest {
}
"""
)

@Issue("https://github.com/openrewrite/rewrite-logging-frameworks/issues/69")
@Test
fun shouldRenameLoggerFromMethodInvocationToClass() = assertChanged(
before = """
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class WrongClass {}
class A {
private Logger logger = LoggerFactory.getLogger(getClass());
}
""",
after = """
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class WrongClass {}
class A {
private Logger logger = LoggerFactory.getLogger(A.class);
}
"""
)

@Test
fun shouldNotChangeCorrectLoggername() = assertUnchanged(
before = """
Expand Down

0 comments on commit 4923215

Please sign in to comment.