Java Logging with SLF4J and Log4j 2

Last update: 2025-08-15 19:45:52 +0800 +0800
tags: Java | Log4j2 | Logging | Slf4j
Available translations: 日本語 / 中文(简体) / 中文(繁體)

SLF4J is a logging API facade. Application code should depend on slf4j-api, while deployment selects one compatible provider such as Log4j 2 or Logback. SLF4J 2 discovers providers through ServiceLoader; retain exactly one. With Log4j 2, log4j-slf4j2-impl adapts SLF4J to Log4j Core. Do not combine it with log4j-to-slf4j, because events then re-enter the facade and form a bridge loop.

java
private static final Logger log = LoggerFactory.getLogger(Orders.class);
log.info("Accepted order {}", orderId);
log.warn("Order {} failed validation", orderId, exception);

Parameterized messages defer formatting while the level is disabled. Use an explicit exception argument rather than interpolating a stack trace into text.

Hierarchy and Configuration #

Logger names form a dot-separated hierarchy. A child inherits the nearest configured level when it has none; common ordered levels are TRACE, DEBUG, INFO, WARN, ERROR, and FATAL in Log4j 2. Log4j 2 routes an event through a matching LoggerConfig and, by default, its ancestors’ appenders. Set additivity="false" only when a dedicated appender must not also feed parent appenders, otherwise duplicate events result.

Appenders are destinations; layouts serialize events. Log4j Core provides console, rolling-file, socket, and other appenders plus pattern and JSON layouts. Its plugin system discovers @Plugin extension types and maps configuration elements to supported implementations. Configuration discovery honors an explicit log4j2.configurationFile, then classpath conventions; use an explicit production location where packaging ambiguity is possible.

Log4j 2 can monitor a local configuration using monitorInterval. Reloading changes a live system, thus validate configuration in deployment and ensure a reload cannot temporarily select unsafe levels, destinations, or credentials.

Operational Data #

Place correlation identifiers and stable request metadata in SLF4J MDC/Log4j Thread Context, then clear context in finally blocks and executor wrappers to prevent cross-request leakage. Prefer structured fields where the backend can index them. Never log passwords, tokens, session identifiers, private keys, or unredacted personal data; redact before constructing the log event. Restrict configuration writes and plugin loading because logging configuration is executable operational policy.

References #

Comments

Read or comment on GitHub (sign-in required to comment)