GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

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

@ds-xdev

@ds-xdev ds-xdev commented Nov 17, 2026 •
edited by timtebeek
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Problem

Log4j 2 evaluates the arguments of logger.debug(String, Object...) and the other level methods before it checks whether the level is enabled. An argument that does real work, such as order.computeTotal(), is paid for on every call, even when the statement is never logged. The same holds for a message that is put together at the call, such as "Hello " + name. Log4j 2.4 added Supplier<?> overloads for this, but there is no recipe that moves existing calls to them.

Before

logger.debug("Order {} costs {}", order.getId(), order.computeTotal());
logger.log(Level.DEBUG, marker, "Loaded {}", repository.count());
logger.debug("Result {}", supplier.get());
logger.debug("Hello " + name);
logger.error("Failed " + name, e);

After

logger.debug("Order {} costs {}", () -> order.getId(), () -> order.computeTotal());
logger.log(Level.DEBUG, marker, "Loaded {}", () -> repository.count());
logger.debug("Result {}", () -> supplier.get());
logger.debug(() -> "Hello " + name);
logger.error(() -> "Failed " + name, e);

Fix

The new ParameterizedLoggingToLambdaSuppliers rewrites Log4j 2 calls to the Supplier<?> overloads. It covers trace through fatal, log(Level, ..) and the Marker variants, and keeps the line breaks and comments around the arguments of the original call. Only Java sources are converted; Kotlin, Groovy and other languages are skipped, since the lambdas come from a Java template.

Two kinds of calls are converted:

  • Parameterized calls. Every parameter is wrapped in a lambda, when at least one argument does real work. Calls whose arguments are all cheap, such as literals, variables, field accesses, simple getters, and casts, array accesses, ternaries or operators over those, are left as they are; there is no option to convert them, since a lambda around a cheap value defers nothing.
  • Composed messages. A String message without parameters that does real work at the call, such as a concatenation, a method call, or a ternary with such a branch, is passed as a supplier. A trailing Throwable stays as it is.

The logLevels option limits the recipe to some levels, e.g. trace, debug. A log(..) call whose level is not a Level constant is then left unchanged.

A call is left unchanged when there is no matching overload, or when the lambda would not compile or would change behaviour.

Converted

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)

Left unchanged

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.

Shared checks

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.

Log4j 2.x best practices

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.

Open questions

  1. A 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?
  2. A parameterized call with a trailing 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?

Verification

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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@moderne-meeseeks moderne-meeseeks Bot added this to OpenRewrite Nov 17, 2026
@moderne-meeseeks moderne-meeseeks Bot assigned ds-xdev Nov 17, 2026
@github-project-automation github-project-automation Bot moved this to In Progress in OpenRewrite Nov 17, 2026
@ds-xdev
ds-xdev marked this pull request as draft November 17, 2026 14:11
@ds-xdev ds-xdev changed the title Add recipe to pass Log4j parameters as lambda suppliers Add recipe to pass Log4j parameters and composed messages as lambda suppliers Nov 19, 2026
@ds-xdev
ds-xdev marked this pull request as ready for review November 19, 2026 13:02
@ds-xdev
ds-xdev requested a review from timtebeek November 19, 2026 13:02
@timtebeek timtebeek mentioned this pull request Nov 19, 2026
Look into casts, array accesses and ternaries for expensive log arguments #331
Merged
@timtebeek
timtebeek force-pushed the ds/log4j-lambda-supplier-parameters branch from 9995f28 to c0c223b Compare November 19, 2026 18:04
@timtebeek
timtebeek changed the base branch from main to tim/share-expensive-log-argument-check November 19, 2026 18:04
@timtebeek
timtebeek added this pull request to stack #332 November 19, 2026 18:07
Base automatically changed from tim/share-expensive-log-argument-check to main November 19, 2026 18:09
ds-xdev and others added 7 commits November 19, 2026 19:09
@ds-xdev @timtebeek
Add recipe to pass Log4j parameters as lambda suppliers
f94d072
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.
@ds-xdev @timtebeek
Keep line breaks in converted log calls and convert variable levels
861c1ec
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.
@ds-xdev @timtebeek
Wrap Supplier.get() and keep arguments that are suppliers
dd33f26
`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.
@ds-xdev @timtebeek
Keep comments and line breaks after converted log arguments
997a3f4
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.
@ds-xdev @timtebeek
Pass composed log messages as suppliers
3dcb4f7
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.
@ds-xdev @timtebeek
Skip Kotlin and Groovy sources and narrow composed messages
7b17522
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.
@timtebeek
Use the shared expensive-argument check for Log4j suppliers
9808b4c
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()`.
@timtebeek
timtebeek force-pushed the ds/log4j-lambda-supplier-parameters branch from c0c223b to 9808b4c Compare November 19, 2026 18:09
@ds-xdev
Merge branch 'main' into ds/log4j-lambda-supplier-parameters
e008eb6
@ds-xdev

ds-xdev commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

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 Supplier passed as an argument

An argument that is a Supplier itself (Log4j's or java.util.function) 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 it changes what is logged.

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 Throwable

Parameterized calls with a trailing Throwable are left unchanged. Converting them is safe at runtime: Log4j still logs the stack trace when the last supplier returns the Throwable (checked with Log4j 2.11.2 to 2.26.1). But () -> e defers nothing and is harder to read than a plain e, and there is no (String, Supplier<?>..., Throwable) overload to use instead.

// 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 compute() worth the less readable call for you?

3. Concatenated messages and log4j.ParameterizedLogging

Both recipes change a message that is put together with +, in different ways. Each leaves the statement alone once the other has changed it, so the order decides. No existing composite runs both, so nothing is affected today.

// source
logger.debug("Hello " + name);

// ParameterizedLoggingToLambdaSuppliers (this PR)
logger.debug(() -> "Hello " + name);

// log4j.ParameterizedLogging (existing)
logger.debug("Hello {}", name);

The overlap is only the + concatenation; ParameterizedLogging does not touch messages such as String.format(..) or name.trim(). The two recipes also work well together in one order: ParameterizedLogging first, then this recipe.

// source
logger.debug("Hello " + compute());

// after log4j.ParameterizedLogging, then this recipe
logger.debug("Hello {}", () -> compute());

Two ways to settle it:

  • this recipe skips + concatenations and leaves them to ParameterizedLogging, and only converts other composed messages such as String.format(..), or
  • both stay as they are and a composite fixes the order (see 4).

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 list.size(). On info, warn and error statements that adds a lambda for little gain.

logger.info("Loaded {} entries", list.size());
// becomes
logger.info("Loaded {} entries", () -> list.size());

Would a Log4jBestPractices composite, next to Slf4jBestPractices, be the right place? It could run ParameterizedLogging first and this recipe for trace and debug only:

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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@timtebeek
Keep side effects and checked exceptions out of deferred log arguments
65c7594
`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.
@timtebeek timtebeek mentioned this pull request Nov 21, 2026
Keep side effects and checked exceptions out of deferred log arguments #340
Merged
timtebeek added 3 commits November 21, 2026 17:04
@timtebeek
Merge branch 'tim/share-lambda-safety-checks' into ds/log4j-lambda-su…
b542003
…pplier-parameters
@timtebeek
Use the shared lambda checks for Log4j suppliers
a0b10ad
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`.
@timtebeek
Merge remote-tracking branch 'origin/main' into ds/log4j-lambda-suppl…
8f0c73c
…ier-parameters
@timtebeek
timtebeek removed this pull request from stack #332 November 21, 2026 16:21
timtebeek added 2 commits November 21, 2026 17:23
@timtebeek
Drop the option to convert simple arguments
edbb489
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.
@timtebeek
Only convert Java sources
7b6f200
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.
timtebeek added 3 commits November 23, 2026 10:27
@timtebeek
Add Log4j 2.x best practices
39223df
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.
@timtebeek
Split the selected levels test into converted and unchanged statements
96ab9f2
@timtebeek
Separate converted and unchanged statements in the selected levels test
cb9addd
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.
@ds-xdev

ds-xdev commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the changes, @timtebeek. I went through them and they look good to me: the shared checks from LogArguments and Scope.lambdaCanCapture, dropping convertSimpleArguments, the JavaFileChecker precondition and the new Log4j2BestPractices composite. The tests of both recipes pass locally.

Two questions from the description are still open. Both cases are left unchanged today, and I would keep it that way for now:

  1. A Supplier passed as an argument. logger.debug("Hello {}", name) with a Supplier<String> name logs the supplier object, not its value. Converting it to name::get would probably match the author's intent, but changes what is logged.
  2. A parameterized call with a trailing Throwable. logger.error("Failed {}", compute(), e) could become logger.error("Failed {}", () -> compute(), () -> e), since Log4j still logs the stack trace. That defers compute(), but () -> e is harder to read than a plain e.

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?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

timtebeek added 3 commits November 24, 2026 17:03
@timtebeek
Inline the preconditions of the Log4j supplier recipe
d82edb2
@timtebeek
Put the precondition and the visitor of the Log4j supplier recipe on …
9d2c959
…their own lines
@timtebeek
Inline single-use type and side-effect helpers in the Log4j supplier …
149805c
…recipe
@timtebeek
timtebeek merged commit 2c5f11a into main Nov 24, 2026
1 check passed

Uh oh!

There was an error while loading. Please reload this page.

@timtebeek
timtebeek deleted the ds/log4j-lambda-supplier-parameters branch November 24, 2026 16:13
@github-project-automation github-project-automation Bot moved this from In Progress to Done in OpenRewrite Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@timtebeek timtebeek Awaiting requested review from timtebeek

Uh oh!

There was an error while loading. Please reload this page.

Assignees

@ds-xdev ds-xdev

Labels

None yet

Projects

OpenRewrite
Status: Done

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

2 participants

@ds-xdev @timtebeek
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.