Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SLF4J 2.x to Log4j API rewrite rule #134

Merged
merged 2 commits into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,12 @@ dependencies {

testRuntimeOnly("org.openrewrite:rewrite-java-17")
testRuntimeOnly("commons-logging:commons-logging:1.2")
testRuntimeOnly("ch.qos.logback:logback-classic:1.2.11")
testRuntimeOnly("ch.qos.logback:logback-classic:1.3.11")

testRuntimeOnly("org.apache.logging.log4j:log4j-core:2.+")
testRuntimeOnly("org.apache.logging.log4j:log4j-api:2.+")

testRuntimeOnly("org.slf4j:slf4j-api:1.+")
testRuntimeOnly("org.slf4j:slf4j-api:2.+")
testRuntimeOnly("log4j:log4j:1.+")

testRuntimeOnly("commons-logging:commons-logging:1.+")
Expand Down
81 changes: 81 additions & 0 deletions src/main/resources/META-INF/rewrite/log4j.yml
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,84 @@ recipeList:
newFullyQualifiedTypeName: org.apache.logging.log4j.Logger
- org.openrewrite.java.logging.ChangeLombokLogAnnotation:
loggingFramework: Log4j2
---
type: specs.openrewrite.org/v1beta/recipe
name: org.openrewrite.java.logging.log4j.Slf4jToLog4j
displayName: Migrate SLF4J to Log4j 2.x API.
description: Transforms code written using SLF4J to use Log4j 2.x API.
tags:
- logging
- slf4j
- log4j
recipeList:
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.LoggerFactory getLogger(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.LogManager
# We intentionally don't rewrite `getDetachedMarker` to cause a compilation error.
# A common usage of detached markers is to "extend" SLF4J to accept objects as messages,
# The Log4j API neither supports nor recommends such a usage. A manual rewrite is required:
# https://github.com/apache/logging-log4j2/pull/770#issuecomment-1072954499
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.MarkerFactory getMarker(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.MarkerManager
# MDC calls
# The target class of this one is an exception
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.MDC putCloseable(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.CloseableThreadContext
- org.openrewrite.java.ChangeMethodName:
methodPattern: org.apache.logging.log4j.CloseableThreadContext putCloseable(..)
newMethodName: put
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.MDC clear(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.ThreadContext
- org.openrewrite.java.ChangeMethodName:
methodPattern: org.apache.logging.log4j.ThreadContext clear(..)
newMethodName: clearAll
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.MDC put(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.ThreadContext
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.MDC get(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.ThreadContext
- org.openrewrite.java.ChangeMethodTargetToStatic:
methodPattern: org.slf4j.MDC remove(..)
fullyQualifiedTargetTypeName: org.apache.logging.log4j.ThreadContext
# Method name changes:
# - No change required for Logger's methods `debug`, `error`, `info`, `trace`,
# `warn`, `getName`, `at*` and `is*Enabled`.
- org.openrewrite.java.ChangeMethodName:
methodPattern: org.slf4j.spi.LoggingEventBuilder addMarker(..)
newMethodName: withMarker
- org.openrewrite.java.ChangeMethodName:
methodPattern: org.slf4j.spi.LoggingEventBuilder setCause(..)
newMethodName: withThrowable
# Change types
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.slf4j.Logger
newFullyQualifiedTypeName: org.apache.logging.log4j.Logger
# The types are different: SLF4J's is an enum, Log4j's is a class,
# but they are source-compatible.
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.slf4j.event.Level
newFullyQualifiedTypeName: org.apache.logging.log4j.Level
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.slf4j.spi.LoggingEventBuilder
newFullyQualifiedTypeName: org.apache.logging.log4j.LogBuilder
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.slf4j.Marker
newFullyQualifiedTypeName: org.apache.logging.log4j.Marker
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.slf4j.MDC.MDCCloseable
newFullyQualifiedTypeName: org.apache.logging.log4j.CloseableThreadContext.Instance
- org.openrewrite.java.ChangeType:
oldFullyQualifiedTypeName: org.slf4j.MDC
newFullyQualifiedTypeName: org.apache.logging.log4j.CloseableThreadContext
- org.openrewrite.java.dependencies.ChangeDependency:
oldGroupId: org.slf4j
oldArtifactId: slf4j-api
newGroupId: org.apache.logging.log4j
newArtifactId: log4j-api
newVersion: latest.release
- org.openrewrite.java.logging.ChangeLombokLogAnnotation:
loggingFramework: Log4j2
246 changes: 246 additions & 0 deletions src/test/java/org/openrewrite/java/logging/log4j/Slf4jToLog4jTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
/*
* Copyright 2021 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java.logging.log4j;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.java.JavaParser;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;
import org.openrewrite.test.TypeValidation;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.java.Assertions.mavenProject;
import static org.openrewrite.maven.Assertions.pomXml;

class Slf4jToLog4jTest implements RewriteTest {

private static final Pattern VERSION_PATTERN = Pattern.compile("<version>([\\d.]+)</version>");

@Override
public void defaults(RecipeSpec spec) {
// The Gradle test runner has SLF4J 1.7.x on the classpath,
// we need to explicitly specify we want SLF4J 2.x.
spec.recipeFromResource("/META-INF/rewrite/log4j.yml", "org.openrewrite.java.logging.log4j.Slf4jToLog4j")
.parser(JavaParser.fromJavaVersion().classpath("log4j-api", "slf4j-api-2[\\d.]+", "lombok"));
}

@DocumentExample
@Test
void loggerUsage() {
rewriteRun(
//language=java
java(
"""
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;

class Test {
private static final Logger LOGGER = LoggerFactory.getLogger(Test.class);
private static final Marker MARKER = MarkerFactory.getMarker("MARKER");

public static void main(String[] args) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("logger message");
}
LOGGER.warn(MARKER, "Hello {}!", "world");
}
}
""",
"""
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.MarkerManager;

class Test {
private static final Logger LOGGER = LogManager.getLogger(Test.class);
private static final Marker MARKER = MarkerManager.getMarker("MARKER");

public static void main(String[] args) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("logger message");
}
LOGGER.warn(MARKER, "Hello {}!", "world");
}
}
"""
)
);
}

@Test
void mdcConversion() {
rewriteRun(
//language=java
java(
"""
import org.slf4j.MDC;

class Test {
void method() {
MDC.put("key", "value");
try (MDC.MDCCloseable c = MDC.putCloseable("key2", "value2")) {
MDC.get("key2");
}
MDC.remove("key");
MDC.clear();
}
}
""",
"""
import org.apache.logging.log4j.CloseableThreadContext;
import org.apache.logging.log4j.ThreadContext;

class Test {
void method() {
ThreadContext.put("key", "value");
try (CloseableThreadContext.Instance c = CloseableThreadContext.put("key2", "value2")) {
ThreadContext.get("key2");
}
ThreadContext.remove("key");
ThreadContext.clearAll();
}
}
"""
)
);
}

@Test
void logBuilder() {
rewriteRun(
//language=java
java(
"""
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.event.Level;

class Test {
void method(Logger logger, Marker marker, Throwable t) {
logger.atLevel(Level.INFO)
.addMarker(marker)
.setCause(t)
.log("Hello {}!", "world");
}
}
""",
"""
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.Marker;

class Test {
void method(Logger logger, Marker marker, Throwable t) {
logger.atLevel(Level.INFO)
.withMarker(marker)
.withThrowable(t)
.log("Hello {}!", "world");
}
}
"""
)
);
}

@Test
void mavenPom() {
rewriteRun(
mavenProject(
"project",
//language=xml
pomXml(
"""
<project>
<groupId>org.example</groupId>
<artifactId>example-lib</artifactId>
<version>1</version>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.9</version>
</dependency>
</dependencies>
</project>
""",
spec -> spec.after(actual -> {
Matcher matcher = VERSION_PATTERN.matcher(actual);
List<String> versions = new ArrayList<>();
while (matcher.find()) {
versions.add(matcher.group(1));
}
return String.format("""
<project>
<groupId>org.example</groupId>
<artifactId>example-lib</artifactId>
<version>%s</version>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>%s</version>
</dependency>
</dependencies>
</project>
""", versions.size() > 0 ? versions.get(0) : "", versions.size() > 1 ? versions.get(1) : "");
}
)
)
)
);
}

@Test
void changeLombokLogAnnotation() {
rewriteRun(spec -> spec.typeValidationOptions(TypeValidation.builder()
.identifiers(false)
.methodInvocations(false)
.build()),
//language=java
java(
"""
import lombok.extern.slf4j.Slf4j;

@Slf4j
class Test {
void method() {
log.info("uh oh");
}
}
""",
"""
import lombok.extern.log4j.Log4j2;

@Log4j2
class Test {
void method() {
log.info("uh oh");
}
}
"""
)
);
}
}