GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — Add recipe to pass Log4j parameters and composed messages as lambda suppliers by ds-xdev · Pull Request #330 · openrewrite/rewrite-logging-frameworks Conversation
|
| Case | Example |
|---|---|
| Argument that does real work | logger.debug("{}", compute()) |
| Mixed cheap and expensive arguments, all wrapped | logger.debug("{} {}", id, compute()) |
| Every level method | trace, debug, info, warn, error, fatal |
log(..) with a Level constant or variable |
logger.log(Level.DEBUG, "{}", compute()) |
Marker variants |
logger.debug(marker, "{}", compute()) |
| More parameters than the fixed overloads take | logger.debug("{} {} ...", a(), b(), ...) |
Supplier.get(), Log4j and java.util.function |
logger.debug("{}", supplier.get()) |
| Composed message | logger.debug("Hello " + name), logger.debug(String.format("Hello %s", name)), logger.debug(name.trim()), logger.debug(flag ? "a" : compute()) |
Composed message with Throwable |
logger.error("Failed " + name, e) becomes logger.error(() -> "Failed " + name, e) |
| Case | Example | Reason |
|---|---|---|
| Only cheap arguments | logger.debug("{} {}", id, getName()), logger.debug("{}", id == null ? "none" : id) |
nothing to defer |
Parameters with a trailing Throwable |
logger.error("Failed {}", compute(), e) |
kept conservatively, see open questions |
| Explicit array | logger.debug("{} {}", params) |
would be logged as one parameter |
| Captured local that is not effectively final | logger.debug("{}", String.valueOf(i)) or logger.debug("Round " + i) in a for loop |
lambda would not compile |
| Assignment or increment in an argument | logger.debug("{}", String.valueOf(counter++)) |
side effect would no longer always run |
| Checked exception | logger.debug("{}", load()) |
lambda would not compile |
| Constant message | logger.debug("no params"), logger.debug("first part " + "second part") |
nothing to defer; literals are joined by the compiler |
Message that is a variable or not a String |
logger.debug(name), logger.debug(object) |
nothing to defer |
| Message that is not put together | logger.debug(flag ? "a" : "b"), logger.debug((String) o), logger.debug(names[0]) |
nothing to defer |
| Lambda or method reference | logger.debug("{}", () -> compute()), logger.debug("{}", this::compute) |
already uses the supplier overload |
| Supplier value as argument | logger.debug("{}", supplier), logger.debug("{}", (Supplier<?>) this::compute) |
resolves to the Object overload and is logged as an object; wrapping it defers nothing |
| Supplier array | logger.debug("{} {}", suppliers) |
already uses the supplier overload |
| Supplier as the message | logger.debug(() -> "Total " + compute()), logger.debug(supplier, e) |
already a supplier |
Level outside logLevels, or not a constant |
logger.log(level, "{}", compute()) with logLevels: debug |
level cannot be checked |
Method calls with side effects, such as iterator.next(), are not detected and are converted; they then only run when the level is enabled.
Builds on #331, which moved the check for expensive arguments into LogArguments.isExpensive, and on #340, which added LogArguments.hasSideEffects and LogArguments.mayThrowCheckedException and uses them in WrapExpensiveLogStatementsInConditionals. This recipe uses the same three checks, and asks Scope.lambdaCanCapture from rewrite-java whether a lambda can capture the locals an argument reads, as the SLF4J recipe does. It treats record accessors as simple getters and needs no special case for Supplier.get(): a method named just get or is is not a getter.
A new Log4j2BestPractices composite, the Log4j counterpart of Slf4jBestPractices, runs the recipes that support Log4j 2.x: ArgumentArrayToVarargs, LoggingExceptionConcatenationRecipe, log4j.ParameterizedLogging, this recipe with logLevels: trace, debug, CatchBlockLogLevel and ChangeLoggersToPrivate. Restricting the levels keeps it off info and above, where most matches have cheap arguments and the lambda saves nothing. ParameterizedLogging runs first, so logger.debug("Hello " + name) becomes logger.debug("Hello {}", name) and only arguments that do real work are passed as suppliers.
java.util.function.Supplier passed as an argument is left unchanged, because Log4j logs the supplier object, not its value. Converting it to supplier::get would probably match the author's intent, but changes what is logged. Should the recipe do that?Throwable is left unchanged. With Log4j 2.26.1, logger.error("{}", () -> x, () -> e) still logs the stack trace, so these calls could be converted too. Is that wanted?Added ParameterizedLoggingToLambdaSuppliersTest, which also asserts that the converted call resolves to the Supplier<?> overload, and updated recipes.csv. Added Log4j2BestPracticesTest. Verified with ./gradlew check before the shared checks, and with ./gradlew test recipeCsvValidate after adding the composite (570 tests, none failing).
Before composed messages were added, the recipe was also run on apache/pdfbox (42 statements in 30 files) and apache/logging-flume (14 statements in 8 files); the main sources of both compiled afterwards, test sources were not compiled. These runs have not been repeated with composed messages.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
9995f28 to
c0c223b
Compare
Log4j 2 evaluates the arguments of `logger.debug(String, Object...)` and
the other level methods before it checks whether the level is enabled.
The new `ParameterizedLoggingToLambdaSuppliers` rewrites these calls to
the `Supplier<?>...` overloads, e.g. `logger.debug("{}", compute())` to
`logger.debug("{}", () -> compute())`, so the arguments are only
evaluated when the statement is logged. It covers `trace` through
`fatal`, `log(Level, ..)` and the `Marker` variants.
By default a call is only converted when at least one argument does real
work; `convertSimpleArguments` converts calls with only literals,
variables, field accesses and simple getters too. `logLevels` limits the
recipe to some levels, e.g. `trace, debug`.
Calls are kept when there is no matching overload or the lambda would
not compile or would change behaviour: a trailing `Throwable`, an
explicit `Object[]`, captured locals that are not effectively final,
arguments with assignments or increments, and calls that throw checked
exceptions.
The replaced call kept only the template's formatting, so log statements spread over several lines were joined into one. The arguments of the converted call now keep their original prefixes. Without `logLevels`, `log(level, ..)` with a level that is not a `Level` constant is converted too. No-change tests are grouped in a nested class.
`supplier.get()` was treated as a simple getter, so a call such as
`logger.debug("{}", supplier.get())` was only converted with
`convertSimpleArguments`. It now counts as an argument that does real
work, for both the Log4j and the `java.util.function` supplier.
An argument that is a supplier itself resolves to the `Object` overload
and is logged as an object. Wrapping it produced code such as
`() -> (Supplier<?>) this::compute` without deferring anything, so
these statements are now left unchanged.
Tests cover lambdas, method references, supplier variables, supplier
arrays, casts and suppliers as the message.
A comment after an argument, such as `compute() /* total */`, was dropped, and a closing parenthesis on its own line was pulled up, because the new lambdas replaced the arguments together with the space that follows them. The converted arguments now keep that space. The comment on the trailing `Throwable` check no longer claims that there is no matching overload: Log4j logs a `Throwable` returned by the last supplier with its stack trace as well, so these calls are kept out of caution only.
A message without parameters that is put together at the call, such as
`logger.debug("Hello " + name)`, was left unchanged because there was
nothing to wrap. The string is still built before Log4j checks the
level, so such a message is now passed as a supplier:
`logger.debug(() -> "Hello " + name)`. A trailing `Throwable` stays as
it is.
Constant messages, including literals joined with `+`, messages that
are a plain variable and messages that are not a `String` are left
unchanged. The checks for side effects, checked exceptions and captured
locals that are not effectively final apply to the message as well.
On a Kotlin file the recipe produced invalid code such as
`logger.debug("Name {}", { () -> name.trim()})`, because the lambdas
come from a Java template. Kotlin and Groovy sources are now skipped,
as `ParameterizedLogging` does.
A message was treated as composed whenever it was not a literal,
variable or field access, so a ternary, a cast or an array access was
wrapped in a lambda although nothing is put together. Only
concatenations and method calls are converted now.
The display name mentions composed messages, and the Javadoc on a
private helper is a plain comment.
The Log4j recipe had its own copy of the check for arguments worth deferring, which treated any cast, array access or ternary as expensive, and narrowed composed messages to concatenations and method calls to compensate. It now uses `LogArguments.isExpensive`, so a message or parameter is converted when some part of it does real work, such as `flag ? "a" : compute()`.
c0c223b to
9808b4c
Compare
|
Here are the four open questions I mentioned. Each one comes with an example and what I would do by default, so a short yes or no should be enough. 1. A An argument that is a Supplier<String> name = () -> loadName(); // today, left unchanged: logs the supplier object logger.debug("Hello {}", name); // possible conversion: logs the value logger.debug("Hello {}", name::get); My default: leave it as is here, and do the conversion in a separate recipe if it is wanted at all. Do you agree? 2. Trailing Parameterized calls with a trailing // today, left unchanged logger.error("Failed for {}", compute(), e); // possible conversion logger.error("Failed for {}", () -> compute(), () -> e); My default: keep these calls unchanged. Is the deferred 3. Concatenated messages and Both recipes change a message that is put together with // source logger.debug("Hello " + name); // ParameterizedLoggingToLambdaSuppliers (this PR) logger.debug(() -> "Hello " + name); // log4j.ParameterizedLogging (existing) logger.debug("Hello {}", name); The overlap is only the // source logger.debug("Hello " + compute()); // after log4j.ParameterizedLogging, then this recipe logger.debug("Hello {}", () -> compute()); Two ways to settle it:
My default: the second, because a concatenation with only cheap parts then still becomes a supplier when the recipe runs on its own. Which do you prefer? 4. Composite The recipe is not part of a composite yet. With the default options it also converts arguments that it counts as real work but that are cheap in practice, such as logger.info("Loaded {} entries", list.size()); // becomes logger.info("Loaded {} entries", () -> list.size()); Would a type: specs.openrewrite.org/v1beta/recipe name: org.openrewrite.java.logging.log4j.Log4jBestPractices displayName: Log4j best practices description: Applies best practices to logging with Log4j 2. preconditions: - org.openrewrite.Singleton tags: - logging - log4j recipeList: - org.openrewrite.java.logging.log4j.ParameterizedLogging - org.openrewrite.java.logging.log4j.ParameterizedLoggingToLambdaSuppliers: logLevels: [trace, debug] My default: add this composite in a follow-up PR, not in this one. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
`WrapExpensiveLogStatementsInConditionals` moved an argument that throws a checked exception into a supplier lambda, as in `logger.atInfo().addArgument(() -> load())`, which does not compile. It also deferred arguments such as `String.valueOf(count++)`, so the increment only ran when the level was enabled. A call whose expensive arguments may throw a checked exception is now wrapped in a level check instead of converted to the fluent API, and a call with an assignment or increment in an argument is left unchanged. The checks live in `LogArguments` so the Log4j supplier recipe can share them.
…pplier-parameters
The side-effect and checked-exception checks now come from `LogArguments`, and whether a lambda can capture the locals an argument reads from `Scope.lambdaCanCapture`, as in `WrapExpensiveLogStatementsInConditionals`.
A boolean option doubles the combinations to reason about and test. Wrapping arguments that are all cheap only adds a lambda allocation, so a statement is now always left unchanged unless at least one argument does real work.
The lambdas come from a Java template, so a `JavaFileChecker` precondition states what the recipe supports directly, rather than ruling out Kotlin and Groovy one by one.
SLF4J and JBoss Logging have a best practices composite, Log4j 2.x had none. It runs the recipes that support Log4j 2.x, and passes trace and debug arguments that do real work as suppliers. `ParameterizedLogging` runs first, so a concatenated message becomes placeholders and only the arguments that do real work are deferred.
Keep a single test, with the statements of the selected levels in one method and those of other levels in another, instead of two tests.
|
Thanks for the changes, @timtebeek. I went through them and they look good to me: the shared checks from Two questions from the description are still open. Both cases are left unchanged today, and I would keep it that way for now:
Neither needs to block this; both could be handled in a follow-up if wanted. From my side this is ready to merge. Is there anything else you'd like to see first? |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.