-
Notifications
You must be signed in to change notification settings - Fork 29
Apply do no harm to ParameterizedLogging by not changing statements with exceptions
#264
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a7437ba
Reduce casting to Object to situations that are ambiguous.
Laurens-W aff3f14
Polish
Laurens-W ce00760
Polish
Laurens-W 3a9f791
Apply do no harm; when an exception is logged do not change anything …
Laurens-W f4b9cb5
Apply suggestions from code review
timtebeek File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
96 changes: 96 additions & 0 deletions
96
src/main/java/org/openrewrite/java/logging/ConvertLoggingExceptionCastToToString.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| /* | ||
| * Copyright 2025 the original author or authors. | ||
| * <p> | ||
| * Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license | ||
| * <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; | ||
|
|
||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Value; | ||
| import org.openrewrite.*; | ||
| import org.openrewrite.internal.ListUtils; | ||
| import org.openrewrite.java.JavaIsoVisitor; | ||
| import org.openrewrite.java.JavaTemplate; | ||
| import org.openrewrite.java.MethodMatcher; | ||
| import org.openrewrite.java.tree.J; | ||
| import org.openrewrite.java.tree.TypeUtils; | ||
|
|
||
| import java.util.Arrays; | ||
| import java.util.HashSet; | ||
| import java.util.Set; | ||
|
|
||
| @EqualsAndHashCode(callSuper = false) | ||
| @Value | ||
| public class ConvertLoggingExceptionCastToToString extends Recipe { | ||
|
|
||
| @Option(displayName = "Method pattern", | ||
| description = "A method pattern to find matching logging statements to update.", | ||
| example = "org.slf4j.Logger debug(..)") | ||
| String methodPattern; | ||
|
|
||
| @Override | ||
| public String getDisplayName() { | ||
| return "Convert Logging exception cast to toString() call"; | ||
| } | ||
|
|
||
| @Override | ||
| public String getDescription() { | ||
| //language=markdown | ||
| return "Converts `(Object) exception` casts in logging statements to `exception.toString()` calls. " + | ||
| "This is more explicit about the intent to log the string representation of the exception " + | ||
| "rather than relying on implicit toString() conversion through Object casting." + | ||
| "Run this after ParameterizedLogging is applied to reduce RSPEC-S1905 findings."; | ||
| } | ||
|
|
||
| @Override | ||
| public Set<String> getTags() { | ||
| return new HashSet<>(Arrays.asList("Logging", "RSPEC-S1905")); | ||
| } | ||
|
|
||
| @Override | ||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||
| return new JavaIsoVisitor<ExecutionContext>() { | ||
| private final MethodMatcher methodMatcher = new MethodMatcher(methodPattern, true); | ||
|
|
||
| @Override | ||
| public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) { | ||
| J.MethodInvocation m = super.visitMethodInvocation(method, ctx); | ||
|
|
||
| // Check if this matches our target method pattern | ||
| if (!methodMatcher.matches(m)) { | ||
| return m; | ||
| } | ||
|
|
||
| JavaTemplate toStringTemplate = JavaTemplate.builder("#{any(java.lang.Throwable)}.toString()") | ||
| .build(); | ||
|
|
||
| m = m.withArguments(ListUtils.map(m.getArguments(), arg -> { | ||
| if (arg instanceof J.TypeCast) { | ||
| J.TypeCast cast = (J.TypeCast) arg; | ||
| if (cast.getType() != null && | ||
| TypeUtils.isOfClassType(cast.getType(), "java.lang.Object") && | ||
| TypeUtils.isAssignableTo("java.lang.Throwable", cast.getExpression().getType())) { | ||
| return toStringTemplate.apply( | ||
| new Cursor(getCursor(), arg), | ||
| arg.getCoordinates().replace(), | ||
| cast.getExpression()); | ||
| } | ||
| } | ||
| return arg; | ||
| })); | ||
|
|
||
| return m.equals(method) ? method : m; | ||
| } | ||
| }; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
195 changes: 195 additions & 0 deletions
195
src/test/java/org/openrewrite/java/logging/ConvertLoggingExceptionCastToToStringTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,195 @@ | ||
| /* | ||
| * Copyright 2025 the original author or authors. | ||
| * <p> | ||
| * Licensed under the Moderne Source Available License (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://docs.moderne.io/licensing/moderne-source-available-license | ||
| * <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; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.openrewrite.DocumentExample; | ||
| import org.openrewrite.InMemoryExecutionContext; | ||
| import org.openrewrite.java.JavaParser; | ||
| import org.openrewrite.test.RecipeSpec; | ||
| import org.openrewrite.test.RewriteTest; | ||
|
|
||
| import static org.openrewrite.java.Assertions.java; | ||
|
|
||
| class ConvertLoggingExceptionCastToToStringTest implements RewriteTest { | ||
|
|
||
| @Override | ||
| public void defaults(RecipeSpec spec) { | ||
| spec.parser(JavaParser.fromJavaVersion() | ||
| .classpathFromResources(new InMemoryExecutionContext(), "slf4j-api-2.1.+", "log4j-api-2.+", "log4j-core-2.+")); | ||
| } | ||
|
|
||
| @DocumentExample | ||
| @Test | ||
| void convertThrowableCastToToString() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new ConvertLoggingExceptionCastToToString("org.slf4j.Logger debug(..)")), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.slf4j.Logger; | ||
|
|
||
| class Test { | ||
| static void asInteger(Logger logger, String numberString) { | ||
| try { | ||
| Integer i = Integer.valueOf(numberString); | ||
| } catch (NumberFormatException ex) { | ||
| logger.debug("some big error: {}", (Object) ex); | ||
| } | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| import org.slf4j.Logger; | ||
|
|
||
| class Test { | ||
| static void asInteger(Logger logger, String numberString) { | ||
| try { | ||
| Integer i = Integer.valueOf(numberString); | ||
| } catch (NumberFormatException ex) { | ||
| logger.debug("some big error: {}", ex.toString()); | ||
| } | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void convertMultipleThrowableCasts() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new ConvertLoggingExceptionCastToToString("org.slf4j.Logger info(..)")), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.slf4j.Logger; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Exception e1, RuntimeException e2) { | ||
| logger.info("Errors: {} and {}", (Object) e1, (Object) e2); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| import org.slf4j.Logger; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Exception e1, RuntimeException e2) { | ||
| logger.info("Errors: {} and {}", e1.toString(), e2.toString()); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void doNotChangeNonThrowableCasts() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new ConvertLoggingExceptionCastToToString("org.slf4j.Logger info(..)")), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.slf4j.Logger; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, String str) { | ||
| logger.info("Value: {}", (Object) str); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void doNotChangeNonObjectCasts() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new ConvertLoggingExceptionCastToToString("org.slf4j.Logger info(..)")), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.slf4j.Logger; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Exception ex) { | ||
| logger.info("Error: {}", (Throwable) ex); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void workWithMarkers() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new ConvertLoggingExceptionCastToToString("org.slf4j.Logger info(..)")), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.Marker; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Marker marker, Exception ex) { | ||
| logger.info(marker, "Error occurred: {}", (Object) ex); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.Marker; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Marker marker, Exception ex) { | ||
| logger.info(marker, "Error occurred: {}", ex.toString()); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| @Test | ||
| void workWithLog4j() { | ||
| rewriteRun( | ||
| spec -> spec.recipe(new ConvertLoggingExceptionCastToToString("org.apache.logging.log4j.Logger error(..)")), | ||
| //language=java | ||
| java( | ||
| """ | ||
| import org.apache.logging.log4j.Logger; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Exception ex) { | ||
| logger.error("Failed: {}", (Object) ex); | ||
| } | ||
| } | ||
| """, | ||
| """ | ||
| import org.apache.logging.log4j.Logger; | ||
|
|
||
| class Test { | ||
| static void method(Logger logger, Exception ex) { | ||
| logger.error("Failed: {}", ex.toString()); | ||
| } | ||
| } | ||
| """ | ||
| ) | ||
| ); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.