Skip to content

fix: Prevent LogBuilder memory leak in Log4j API to Logback bridge #3824

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

Open
wants to merge 2 commits into
base: 2.x
Choose a base branch
from

Conversation

ppkarwasz
Copy link
Contributor

This change fixes a potential memory leak in the log4j-to-slf4j module (Logback Log4j API binding) caused by the use of a thread-local LogBuilder pool.

The leak occurred because the thread-local field was accidentally accessed, even when log4j2.enableThreadlocals was set to false. In servlet environments, this could lead to classloader leaks due to the persistence of thread-local references.

With this fix, all access to the ThreadLocal is now properly gated by the log4j2.enableThreadlocals system property—matching how similar pooling behavior is handled in Log4j Core.

This preserves the GC-free option for advanced users who explicitly opt in via log4j2.enableThreadlocals = true, while avoiding memory leaks for others.

Fixes #3819

This change fixes a potential memory leak in the `log4j-to-slf4j` module (Log4j API to Logback bridge) caused by the use of a thread-local `LogBuilder` pool.

The leak occurred because the thread-local field was accessed, even when `log4j2.enableThreadlocals` was set to `false`. In servlet environments, this could lead to classloader leaks due to the persistence of thread-local references.

With this fix, all access to the `ThreadLocal` is now **properly** gated by the `log4j2.enableThreadlocals` system property—matching how similar pooling behavior is handled in Log4j Core.

This preserves the GC-free option for advanced users who explicitly opt in via `log4j2.enableThreadlocals = true`, while avoiding memory leaks for others.

Fixes #3819
The `--add-opens` JVM option is now included in a dedicated Maven profile to avoid applying it during CI builds on JRE 8, where it is unsupported and unnecessary.
Copy link

@gmiscione gmiscione left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code looks ok and the access to the ThreadLocal is correctly gated by the boolean field

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: To triage
Development

Successfully merging this pull request may close these issues.

Using log4j-to-slf4j in a web application incorrectly sets a value in a ThreadLocal in org.apache.logging.slf4j.SLF4JLogger
2 participants