For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/java/logging.md.
Logging is how your application communicates what it is doing at runtime. A good logging
setup helps you debug issues, monitor production health, and audit system behaviour.
The modern Java logging stack has two layers:
Facade - SLF4J (Simple Logging Facade for Java) - your code depends on this
Implementation - Logback or Log4j2 - the actual engine that writes logs
log.trace("Entering method with args: {}, {}", a, b);log.debug("Query returned {} results", results.size());log.info("User {} logged in from {}", userId, ipAddress);log.warn("API rate limit approaching: {}/{}", current, max);log.error("Failed to connect to database", exception);
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.6.3</version></dependency><!-- This transitively includes slf4j-api and logback-core -->
Version management
Keep logging dependencies current and managed via a BOM (e.g. Spring Boot's
dependency management) rather than pinning manually. Check the vendor security
pages (Logback and Apache Log4j) before picking a version.
MDC lets you attach contextual data to every log statement within a thread
(e.g., request ID, user ID, session ID):
import org.slf4j.MDC;// Set in a filter or interceptorpublic void handleRequest(HttpServletRequest req) { MDC.put("requestId", UUID.randomUUID().toString()); MDC.put("userId", req.getHeader("X-User-Id")); try { // All log statements in this thread now include requestId and userId log.info("Handling request"); service.process(); } finally { MDC.clear(); // always clear in finally! }}
Many libraries use different logging APIs. Bridge them all to SLF4J:
<!-- Bridge JCL to SLF4J --><dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>2.0.13</version></dependency><!-- Bridge JUL to SLF4J --><dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>2.0.13</version></dependency><!-- Exclude the original implementations --><!-- (in the dependency that pulls them in) -->