rewrite-logging-frameworks icon indicating copy to clipboard operation
rewrite-logging-frameworks copied to clipboard

ParameterizedLogging should also replace `String.format` / `.formatted`

Open koppor opened this issue 1 year ago • 1 comments

Got:

-            LOGGER.debug(String.format("Could not parse the FileAnnotation %s into any known FileAnnotationType. It was %s!", annotation, annotation.getSubtype()));
+            LOGGER.debug("Could not parse the FileAnnotation %s into any known FileAnnotationType. It was %s!".formatted(annotation, annotation.getSubtype()))

Expected:

LOGGER.debug("Could not parse the FileAnnotation {} into any known FileAnnotationType. It was {}.", annotation, annotation.getSubtype());

Similarly,

-  LOGGER.warn("Unexpected attribute '%s' for <%s>".formatted(key, tagName));
+  LOGGER.warn("Unexpected attribute '{}' for <{}>", key, tagName);

I checked https://github.com/openrewrite/rewrite-logging-frameworks/blob/main/src/test/java/org/openrewrite/java/logging/ParameterizedLoggingTest.java - and there is no test for String.format and .formatted.

koppor avatar May 27 '24 11:05 koppor

Indeed seems like a decent extension of the existing recipe. There's some limitations of course when we can apply such a code change, but good suggestion for the limited cases.

timtebeek avatar May 27 '24 11:05 timtebeek

As helpfully pointed out in #239 this should instead be covered by https://docs.openrewrite.org/recipes/java/logging/slf4j/slf4jlogshouldbeconstant

Hope that helps!

timtebeek avatar Jul 21 '25 09:07 timtebeek

As helpfully pointed out in #239 this should instead be covered by https://docs.openrewrite.org/recipes/java/logging/slf4j/slf4jlogshouldbeconstant

Hope that helps!

I'm trying to understand why similar code lives in two places. Did I fix SLF4J and this PR is for JUL?

motlin avatar Jul 21 '25 14:07 motlin

So while similar these two recipes look to cover slightly different cases:

  • https://docs.openrewrite.org/recipes/java/logging/slf4j/slf4jlogshouldbeconstant
  • https://docs.openrewrite.org/recipes/java/logging/parameterizedlogging

The first focuses mostly on String.format, whereas the second looks at string concatenation. Together they achieve what we're after: logging statements that avoid calculation up front before passing into the logging method. I guess we could update the descriptions to make this clear, or even refer to the other recipe.

timtebeek avatar Jul 21 '25 16:07 timtebeek