MDC Poisoning — SLF4J/Logback Thread Pool Fix
Stale MDC data from thread pool reuse exposes customer data across requests — discover the finally-block fix that prevents false escalations..
20+ years shipping production Java in banking & fintech. Everything here is grounded in real deployments.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- SLF4J is a facade — your code compiles against it, never the logger directly
- Logback provides the native SLF4J binding: no adapter jars needed
- Parameterised logging avoids garbage when log level is disabled, saving CPU in hot paths
- MDC attaches request-scoped keys (customerId) to every log line automatically
- Biggest mistake: not clearing MDC in a finally block — it poisons logs on thread reuse
MDC Poisoning is a subtle but destructive concurrency bug that occurs when using SLF4J's Mapped Diagnostic Context (MDC) with thread pools in Logback. The MDC is a thread-local map that lets you attach contextual data (like request IDs, user IDs, or tenant IDs) to log statements without passing them through every method call.
The problem arises when a thread from a pool finishes processing and its MDC is not cleared — the next task reusing that thread inherits the stale context, causing logs to be attributed to the wrong request. This silently corrupts observability, making debugging, tracing, and alerting unreliable in production systems.
This issue is particularly insidious because it doesn't crash your application or throw exceptions — it just quietly poisons your log data. You'll see mismatched request IDs, phantom users, or cross-tenant data leaks in logs. It's most common in high-throughput async logging setups where you've configured Logback's AsyncAppender or are using thread pools for parallel processing.
The fix involves either manually clearing the MDC in a finally block after each task, using a custom thread pool decorator, or leveraging Logback's built-in MDCInsertingServletFilter with proper cleanup hooks.
In the Java ecosystem, alternatives like Log4j 2 have similar MDC features (called Thread Context) with the same vulnerability. When not to use MDC: if your logging volume is low and you don't need cross-cutting context, or if you're using a reactive framework like Project Reactor where thread-local storage doesn't work — in those cases, pass context explicitly or use Reactor's Context API.
For production systems handling thousands of requests per second, MDC poisoning is a silent killer that turns your logging infrastructure into a liability.
Imagine you're a pilot flying a plane. You don't write down every instrument reading yourself — you have a black box that automatically records everything: speed, altitude, engine status. If something goes wrong, you rewind the tape and see exactly what happened. Java logging is that black box for your application. SLF4J is the dashboard interface your code talks to, and Logback is the actual recorder underneath — and you can swap the recorder out without touching the dashboard.
Every real production application breaks at some point. A user can't check out, an API call silently fails at 2 AM, or a subtle data bug corrupts records for three weeks before anyone notices. The only way you find out what actually happened — not what you think happened — is your logs. Logging isn't a nice-to-have. It's your flight recorder, your audit trail, and your first responder toolkit all in one.
The Java ecosystem has historically been a mess for logging. You had java.util.logging baked into the JDK, then Log4j came along, then Commons Logging tried to abstract over them, then SLF4J did it properly, and now Logback exists as the spiritual successor to Log4j written by the same author. The problem this whole stack solves is simple: your code shouldn't be coupled to a specific logging implementation. Libraries you depend on might use Log4j, your framework might use JUL, and your own code uses Logback — SLF4J bridges them all so everything funnels into one consistent output stream.
By the end of this article you'll understand why the SLF4J facade pattern exists and why it matters, how to set up Logback from scratch with a real configuration file, how to use structured logging patterns that make log searching practical, how to configure rolling file appenders so your server disk doesn't fill up overnight, and the exact mistakes that trip up intermediate developers in interviews and in production.
How SLF4J and Logback Actually Work Together
SLF4J is a logging facade — a thin abstraction layer that decouples your application code from the underlying logging implementation. Logback is a native, high-performance implementation of SLF4J, designed as a direct replacement for Log4j 1.x. The core mechanic: your code calls SLF4J's Logger interface, which delegates to Logback's actual logging engine at runtime via a binding mechanism (logback-classic). This means you can swap implementations without touching a single line of application code.
In practice, Logback introduces three key properties: asynchronous appenders for non-blocking I/O, MDC (Mapped Diagnostic Context) for thread-local contextual data, and a configurable rolling policy for log files. MDC is particularly powerful — it lets you attach request-scoped values (like user ID, transaction ID) to every log line without passing them through method signatures. But MDC is thread-bound: if you use thread pools, the context doesn't propagate automatically. That's where MDC poisoning happens — stale context from a previous task leaks into the next task, corrupting logs and making debugging impossible.
Use this stack when you need a production-grade, configurable logging system that supports structured logging, low-latency output, and contextual enrichment. It matters because in distributed systems, log correlation across services depends on consistent MDC propagation. Without it, you lose traceability — and debugging a production incident becomes a guessing game.
Why SLF4J Exists — The Facade Pattern in Plain English
Here's a scenario that plays out constantly in enterprise Java. Your team writes a library and you pick Log4j 1.x. Six months later the consuming application uses Logback. Now you have two logging frameworks fighting each other in the same JVM, producing duplicate output, different formats, and no unified way to control log levels. This is the dependency hell SLF4J was designed to end.
SLF4J — Simple Logging Facade for Java — is deliberately just an API. It ships as a thin jar with interfaces and no real implementation. Your code calls LoggerFactory.getLogger() and logs via the Logger interface. At runtime, whichever SLF4J-compatible implementation is on the classpath — Logback, Log4j2, java.util.logging — picks up those calls. Think of SLF4J like a power outlet standard. You design your appliance (your code) to plug into the standard outlet shape. Whether the power behind that wall is hydro, solar, or nuclear is not your appliance's concern.
Logback is the natural default choice because its author, Ceki Gülcü, also wrote SLF4J. Logback implements SLF4J natively — no adapter bridge needed — and it's faster, more configurable, and actively maintained. When you add logback-classic to your project, it automatically provides the SLF4J binding. That's why you'll see both on the classpath together.
<!-- Add these dependencies to your Maven pom.xml --> <dependencies> <!-- SLF4J API — the facade your code compiles against. No logging actually happens from this jar alone. --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.13</version> </dependency> <!-- Logback Classic — the actual implementation. This jar ALSO provides the SLF4J binding automatically, so you do NOT need a separate slf4j-logback-binding artifact. --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.5.6</version> </dependency> <!-- logback-classic already pulls in logback-core transitively, so you don't need to declare logback-core explicitly. --> </dependencies>
mvn dependency:tree | grep slf4j to check. Use Maven exclusions to boot the unwanted binding out.mvn dependency:tree before every major release.Your First Real Logback Configuration — logback.xml Explained Line by Line
Logback's configuration lives in logback.xml, placed in src/main/resources. If it can't find this file, Logback falls back to a default configuration that only logs WARN and above to the console. That default will bite you in development when you can't see your DEBUG output and wonder why your code appears to do nothing.
The configuration has three building blocks you need to understand before you write a single line of XML. An Appender is a destination — console, file, socket, database. An Encoder (or Layout) controls the format of each log line. A Logger is a named channel tied to your class hierarchy — you set its level and point it at one or more appenders.
Logback's logger hierarchy is one of its most powerful features. A logger named com.theforge.order is automatically a child of com.theforge, which is a child of the root logger. Set the level on com.theforge to DEBUG and every class in that package inherits it, unless explicitly overridden. This lets you turn on fine-grained debug output for one package in production without drowning in noise from your entire application — a trick that's saved countless late-night debugging sessions.
<?xml version="1.0" encoding="UTF-8"?> <configuration> <!-- ───────────────────────────────────────────── APPENDER: CONSOLE Writes formatted log lines to System.out. Good for local dev and containerised apps where stdout is captured by the platform. ───────────────────────────────────────────── --> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <!-- Pattern breakdown: %d{HH:mm:ss.SSS} — timestamp [%thread] — thread name (vital for async apps) %-5level — log level, left-padded to 5 chars %logger{36} — logger name, truncated to 36 chars - %msg%n — the actual message, then newline --> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- ───────────────────────────────────────────── APPENDER: ROLLING FILE Writes to a file. When the file hits 10MB, it rolls over to a new file. Keeps 30 days of history and caps total size at 1GB so your disk doesn't silently fill up. ───────────────────────────────────────────── --> <appender name="ROLLING_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- The active log file always has this name --> <file>logs/application.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- Archive pattern: one file per day, gzip compressed --> <fileNamePattern>logs/application.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <!-- Roll over when a single file reaches 10MB --> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!-- Keep 30 days of rolled files --> <maxHistory>30</maxHistory> <!-- Hard cap on total log storage across all rolled files --> <totalSizeCap>1GB</totalSizeCap> </rollingPolicy> <encoder> <!-- File logs include the full logger name for easier grepping --> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern> </encoder> </appender> <!-- ───────────────────────────────────────────── PACKAGE-LEVEL LOGGER OVERRIDE Only log DEBUG and above for our own code. This won't affect Hibernate, Spring, or any other library — they stay at their own levels. ───────────────────────────────────────────── --> <logger name="com.theforge" level="DEBUG" additivity="false"> <appender-ref ref="CONSOLE"/> <appender-ref ref="ROLLING_FILE"/> </logger> <!-- ───────────────────────────────────────────── ROOT LOGGER Catches everything not matched by a more specific logger above. Set to WARN in prod to suppress noisy INFO from libraries. ───────────────────────────────────────────── --> <root level="WARN"> <appender-ref ref="CONSOLE"/> <appender-ref ref="ROLLING_FILE"/> </root> </configuration>
Writing Logging Code That Actually Helps in Production
The way most developers log is wrong, and you'll only discover that when you're staring at useless log lines at midnight trying to diagnose a live incident. The three biggest practical mistakes are: using string concatenation instead of parameterised messages, logging at the wrong level, and missing contextual information that would make the log line self-contained.
SLF4J's parameterised logging — logger.debug("Order {} placed by user {}", orderId, userId) — isn't just stylistic. It's a performance optimisation. The string is only assembled if DEBUG is actually enabled. With concatenation, "Order " + orderId + " placed by user " + userId builds the string regardless of level — which inside a hot loop is expensive garbage creation for log lines that are never written.
Log level discipline matters too. Use TRACE for developer-only deep dives you'd never want in production. DEBUG for diagnostic info useful during development and targeted prod debugging. INFO for key business events — order placed, payment processed, user logged in. WARN for recoverable problems that need attention — a retry succeeded, a config value fell back to default. ERROR for failures that require immediate action. The rule of thumb: INFO logs should tell the story of a successful request; WARN and ERROR logs should make the on-call engineer's next steps obvious.
package com.theforge.order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; /** * Real-world service class showing correct SLF4J logging patterns. * Notice the Logger is static final — one instance per class, shared * across all method calls. Creating a new Logger per method call is * wasteful and unnecessary. */ public class OrderService {\n\n // Best practice: logger is static (one per class), final (never reassigned),\n // and named after the class itself for clear log output.\n private static final Logger logger = LoggerFactory.getLogger(OrderService.class);\n\n public Order placeOrder(String customerId, String productSku, int quantity) {\n\n // MDC — Mapped Diagnostic Context — attaches key-value pairs to EVERY\n // log line produced on this thread, automatically. This means if you\n // grep your logs for a customerId, you find ALL related log lines,\n // not just the ones where you remembered to include the id manually.\n MDC.put(\"customerId\", customerId);\n MDC.put(\"productSku\", productSku);\n\n try {\n // INFO: a meaningful business event that always matters\n logger.info(\"Placing order for {} units of SKU {}\", quantity, productSku);\n\n if (quantity > 1000) {\n // WARN: something unusual, but we're still handling it\n logger.warn(\"Large order quantity {} for SKU {} — triggering manual review flag\",\n quantity, productSku);\n }\n\n // DEBUG: internal state useful during development/diagnosis,\n // not noise in normal production operation\n logger.debug(\"Checking inventory for SKU {} — requested qty: {}\", productSku, quantity);\n\n boolean inventoryAvailable = checkInventory(productSku, quantity);\n\n if (!inventoryAvailable) {\n // WARN with context — not an error (expected scenario), but needs attention\n logger.warn(\"Insufficient inventory for SKU {} — requested: {}, available: {}\",\n productSku, quantity, getAvailableStock(productSku));\n throw new InsufficientStockException(productSku, quantity);\n }\n\n Order createdOrder = persistOrder(customerId, productSku, quantity);\n\n // Confirm success with the generated orderId — makes log lines self-contained\n logger.info(\"Order {} successfully created for customer {}\",\n createdOrder.getOrderId(), customerId);\n\n return createdOrder;\n\n } catch (DatabaseException dbEx) {\n // ERROR: include the exception as the LAST parameter so Logback\n // prints the full stack trace automatically. Don't call\n // dbEx.getMessage() yourself — you'll lose the stack trace.\n logger.error(\"Database failure while persisting order for customer {} SKU {}\",\n customerId, productSku, dbEx);\n throw new OrderProcessingException(\"Order persistence failed\", dbEx);\n\n } finally {\n // CRITICAL: always clear MDC at the end of the request/thread boundary.\n // In thread pool environments, threads are reused. If you don't clear,\n // the next request on this thread inherits your customerId in its logs.\n MDC.clear();\n }\n }\n\n // ── Stub methods to make the example compile ──────────────────────────────\n\n private boolean checkInventory(String sku, int qty) {\n return true; // simplified for example\n }\n\n private int getAvailableStock(String sku) {\n return 500; // simplified for example\n }\n\n private Order persistOrder(String customerId, String sku, int qty) {\n return new Order(\"ORD-20240115-7829\", customerId, sku, qty);\n }\n}", "output": "14:23:01.442 [main] INFO c.t.order.OrderService - Placing order for 3 units of SKU WIDGET-42\n14:23:01.445 [main] DEBUG c.t.order.OrderService - Checking inventory for SKU WIDGET-42 — requested qty: 3\n14:23:01.451 [main] INFO c.t.order.OrderService - Order ORD-20240115-7829 successfully created for customer CUST-881\n\nNote: The MDC values (customerId, productSku) appear in each line when your\nlogback.xml pattern includes %X{customerId} and %X{productSku} in the encoder pattern." }
Environment-Specific Configs and Testing Your Log Output
Hard-coding log levels in logback.xml means you need different XML files per environment, which is fragile. Logback supports property substitution, and when combined with Spring Boot's application.properties or plain system properties, you get one XML file that behaves differently in dev, staging, and production without any file duplication.
For testing, the most common pain is log output polluting test console output, or worse — not being able to assert that a specific log message was produced during a test. Logback ships with logback-test.xml, which it prefers over logback.xml when running tests. Put it in src/test/resources with <root level="OFF"/> to silence all logging during tests unless you explicitly opt back in. To assert log output in unit tests, the logback-classic module includes ListAppender, an in-memory appender you can wire up programmatically and inspect after the fact.
This pattern is underused and incredibly valuable. If your PaymentService is supposed to log a WARN when a card is declined, write a test that proves it does. That log message is part of your contract — the on-call engineer depends on it. Testing it like any other behaviour keeps it honest.
package com.theforge.order; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.read.ListAppender; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.LoggerFactory; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** * Proves that OrderService emits the correct log events. * Log messages are part of your observable behaviour — test them. */ class OrderServiceLoggingTest { private ListAppender<ILoggingEvent> logCapture; private Logger orderServiceLogger; private OrderService orderService; @BeforeEach void attachLogCapture() { // Cast to Logback's concrete Logger (not SLF4J's interface) // so we can manipulate it programmatically in the test. orderServiceLogger = (Logger) LoggerFactory.getLogger(OrderService.class); // ListAppender stores every log event in an in-memory list. // Perfect for assertions — no file I/O, no console noise. logCapture = new ListAppender<>(); logCapture.start(); // Attach our capture appender to the service's logger orderServiceLogger.addAppender(logCapture); // Make sure DEBUG events reach us during the test orderServiceLogger.setLevel(Level.DEBUG); orderService = new OrderService(); } @AfterEach void detachLogCapture() { // Always clean up — leaving a stale appender affects other tests orderServiceLogger.detachAppender(logCapture); } @Test void shouldLogInfoWhenOrderIsSuccessfullyPlaced() { orderService.placeOrder("CUST-881", "WIDGET-42", 3); List<ILoggingEvent> capturedEvents = logCapture.list; // Assert that at least one INFO message confirms the order was created assertThat(capturedEvents) .filteredOn(event -> event.getLevel() == Level.INFO) .extracting(ILoggingEvent::getFormattedMessage) .anyMatch(message -> message.contains("successfully created")); } @Test void shouldLogWarnForLargeOrderQuantity() { // A quantity over 1000 should trigger a WARN in OrderService orderService.placeOrder("CUST-002", "BULK-SKU-9", 1500); List<ILoggingEvent> capturedEvents = logCapture.list; assertThat(capturedEvents) .filteredOn(event -> event.getLevel() == Level.WARN) .extracting(ILoggingEvent::getFormattedMessage) .anyMatch(message -> message.contains("Large order quantity")); } @Test void debugMessagesShouldIncludeSkuInformation() { orderService.placeOrder("CUST-333", "GADGET-7", 2); assertThat(logCapture.list) .filteredOn(event -> event.getLevel() == Level.DEBUG) .extracting(ILoggingEvent::getFormattedMessage) .anyMatch(message -> message.contains("GADGET-7")); } }
Async Logging with Logback — Prevent I/O Blocking in High-Throughput Paths
Synchronous file logging blocks the application thread while the log event is written to disk. In high-throughput scenarios — 10,000 requests per second — the cumulative I/O wait can add 30-50ms per request, collapsing throughput and increasing tail latency. Logback's AsyncAppender solves this by offloading log writes to a background thread, returning control to the application immediately.
Under the hood, AsyncAppender wraps a synchronous appender (like RollingFileAppender) and uses a bounded blocking queue. The application thread only enqueues the log event; the async worker thread drains the queue and delegates to the wrapped appender. If the queue is full — either because writes can't keep up or because a disk is slow — the default behaviour discards log events of TRACE, DEBUG, and INFO level, preserving WARN and ERROR. You can control this with the discardingThreshold parameter.
One critical trap: if the JVM crashes, log events still in the queue are lost. For transactions that require audit-trail guarantees, never use async logging alone — use a synchronous log with a dedicated, transaction-safe output (like a database). Async logging is for performance, not durability.
<!-- Wrap the rolling file appender in an async appender --> <appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender"> <!-- Maximum number of log events in the queue before discarding --> <queueSize>512</queueSize> <!-- Discard TRACE/DEBUG/INFO when the queue exceeds this percentage (default 80) --> <discardingThreshold>0</discardingThreshold> <!-- Never block the application thread -- always prefer dropping events --> <neverBlock>true</neverBlock> <!-- The real appender that does I/O (rolling file) --> <appender-ref ref="ROLLING_FILE"/> </appender> <!-- Then reference ASYNC instead of ROLLING_FILE in your logger config --> <logger name="com.theforge" level="DEBUG" additivity="false"> <appender-ref ref="CONSOLE"/> <appender-ref ref="ASYNC"/> </logger>
The One Dependency Mistake That Will Haunt Your Classloader
When your Spring Boot app starts but mysteriously produces zero log output, you've hit the classic SLF4J classpath war. Multiple binding JARs on the classpath cause SLF4J to pick the first one it finds, often NOP (no-operation) implementation. Spring Boot 3.x ships with Logback by default via spring-boot-starter-logging, but the moment you manually add log4j-slf4j-impl or slf4j-simple to your POM, you create a conflict. The fix: never add SLF4J binding dependencies manually. Let Boot's dependency management handle it. If you truly need Log4j2, exclude Logback and add log4j-slf4j2-impl as your single binding. Use 'mvn dependency:tree' to audit for duplicates. First sign of trouble: your info() calls don't print to console. Don't debug that — audit classpath first.
// io.thecodeforge <!-- The ONLY logging dependency you need for Logback in Spring Boot 3.x --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- Exclude default Logback if switching to Log4j2 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- When migrating to Log4j2, add this as the single binding --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency>
How to Silence Third-Party Libraries Without Touching Their Code
Your app logs nicely, but Hibernate throws DEBUG spam on every query and Tomcat logs INFO on every request. You can't modify those libraries. But Logback's logger hierarchy lets you control any package's log level from your logback-spring.xml. The pattern: add a <logger> element specifying the third-party package and set its level to WARN or ERROR. This overrides the root logger for that namespace only. Spring Boot's Profile-specific configs let you elevate these during development and suppress them in production. The WHY: production logs become searchable. A WARN from Hibernate means something blocked a connection. A DEBUG from Tomcat means nothing unless you're debugging a specific issue. Filter by package, not by log level alone.
// io.thecodeforge <configuration> <!-- Your app's custom level --> <logger name="com.yourcompany.orderservice" level="DEBUG" /> <!-- Silence third-party noise --> <logger name="org.hibernate.SQL" level="WARN" /> <logger name="org.apache.tomcat.util.net" level="ERROR" /> <logger name="org.springframework.web" level="WARN" /> <!-- Production root level --> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="FILE" /> </root> <!-- Profile-specific overrides --> <springProfile name="dev"> <logger name="org.hibernate.SQL" level="TRACE" /> </springProfile> </configuration>
MDC Poisoning Caused a False Customer Escalation
MDC.put() at the start of each request but never called MDC.clear() in a finally block. The thread pool reused the thread for the next request, carrying the stale customerId forward.MDC.put() with MDC.clear() in try-finally.- MDC is thread-local — threads in a pool retain it across requests.
- Always clear MDC in a finally block or use a framework filter that does it for you.
- Treat MDC as a resource that must be released, like a database connection.
grep -r logback startup.log to see config loading messages.MDC.clear() isn't called before the log line is written — check placement.df -h and verify the rolling appender's maxFileSize and totalSizeCap.java -jar myapp.jar --debug | grep -i logbackls -la target/classes/logback*.xmlgrep 'level=' $(find . -name 'logback*.xml')Check for multiple logback configs: find . -name '*logback*'grep -r 'MDC.put' src/ -A2 -B2grep -r 'MDC.clear' src/ -A1 -B1MDC.clear(); }.ls -lh logs/application*du -sh logs/grep -r 'logger\.(debug|info|warn|error).*\+' src/Audit hot-path methods: use perf or JFR sampling| Feature / Aspect | SLF4J + Logback | java.util.logging (JUL) |
|---|---|---|
| Setup complexity | Two jars + one XML file | Zero setup — built into JDK |
| Configuration format | logback.xml (flexible, powerful) | logging.properties (limited) |
| Performance | Async appenders, parameterised msgs, very fast | Synchronous, slower in high-throughput scenarios |
| Rolling file support | Built-in: size + time + compression | Requires custom Handler implementation |
| MDC (contextual data) | Built-in MDC with thread-local storage | Not supported natively |
| Log level granularity | TRACE, DEBUG, INFO, WARN, ERROR | FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE |
| Library ecosystem adoption | Dominant — Spring, Hibernate, most OSS uses SLF4J | Rarely used outside legacy JDK internals |
| Testing support | ListAppender, programmatic config | Custom Handler required — boilerplate-heavy |
| Conditional processing | Janino-based conditional config in XML | Not supported |
| Best for | Any non-trivial Java application | Quick scripts or environments with zero external dependencies |
| File | Command / Code | Purpose |
|---|---|---|
| pom.xml | Why SLF4J Exists | |
| logback.xml | Your First Real Logback Configuration | |
| OrderService.java | /** | Writing Logging Code That Actually Helps in Production |
| OrderServiceLoggingTest.java | /** | Environment-Specific Configs and Testing Your Log Output |
| logback.xml (async snippet) | Async Logging with Logback | |
| pom.xml | The One Dependency Mistake That Will Haunt Your Classloader | |
| logback-spring.xml | How to Silence Third-Party Libraries Without Touching Their |
Key takeaways
logger.info("Order {}", orderId))Common mistakes to avoid
5 patternsUsing string concatenation in log statements
logger.debug("Processing order " + orderId) builds the string even when DEBUG is disabled, creating garbage objects and wasting CPU. Profilers show high allocation rates in logging code.logger.debug("Processing order {}", orderId). SLF4J only assembles the string when the log level is active.Forgetting to clear the MDC
MDC.put("userId", userId) at the start of a request and never call MDC.clear() in a finally block, the next request served by that thread inherits a stale userId in all its log lines. This silently poisons your logs.MDC.put() with MDC.clear() in a finally block, or use a Servlet Filter that automatically cleans up after every request.Logging the exception message separately instead of passing the exception as the last argument
logger.error("DB failed: " + e.getMessage()) discards the entire stack trace. When the on-call engineer views the log, they see only a string — no stack frames, no root cause.logger.error("DB failed for order {}", orderId, exception) — the exception goes last, no explicit stack trace printing needed.Using the default logback.xml fallback instead of a custom configuration
Not configuring rolling policies — letting the log file grow indefinitely
Interview Questions on This Topic
Why does SLF4J use a facade pattern instead of being a full logging framework itself? What problem does this solve for library authors specifically?
What is the MDC and why must you always clear it at the end of a request in a servlet container? What's the exact failure mode if you forget?
If you have logback-classic and slf4j-log4j12 both on your classpath, what happens? How would you diagnose it and fix it in a Maven project?
mvn dependency:tree | grep slf4j to see all SLF4J dependencies. Fix by excluding one binding: for example, if logback-classic is desired, exclude slf4j-log4j12 from any transitive dependency that pulls it in.Explain the difference between additivity="true" (default) and additivity="false" in logback.xml. When would you use each?
com.theforge.order also goes to com.theforge and then to the root logger, potentially being written to multiple appenders. Use additivity="true" when you want the root logger's appender to catch all events without needing to add it to every package logger. Use additivity="false" when you define an appender on a package logger and you don't want duplicates — set it to false to prevent the event from propagating to ancestors.How would you configure Logback to log JSON-formatted output for consumption by ELK or similar log aggregators?
logback-contrib or use net.logstash.logback.encoder.LogstashEncoder. Then configure an appender with an encoder class instead of a pattern. Example: <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>. The encoder automatically includes standard fields (timestamp, level, logger, message, thread) and can be configured to include MDC fields.What are the trade-offs between synchronous and asynchronous logging with Logback's AsyncAppender? When would you choose one over the other?
Frequently Asked Questions
Yes, both. The slf4j-api jar is what your code compiles against — it contains only interfaces and no logging logic. The logback-classic jar is the runtime implementation and also provides the SLF4J binding. Without slf4j-api your code won't compile; without logback-classic nothing gets logged at runtime.
Logback falls back to a default BasicConfigurator that logs WARN level and above to the console only, using a minimal pattern. You won't see any DEBUG or INFO output. You'll also see a warning printed to stderr on startup: 'No appenders could be found for logger'. Add a logback.xml to src/main/resources to take control of your configuration.
They're very different in practice. Passing the exception as the last Throwable argument tells SLF4J to print the complete stack trace automatically. Concatenating exception.getMessage() logs only the message string and throws away the entire stack trace and cause chain — making production debugging exponentially harder. Always pass the exception object as the final argument.
Use %X{keyName} in the encoder pattern. For example: <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} [%X{customerId}] - %msg%n</pattern>. This will output the value of MDC key 'customerId' in every log line. If the key is not set, it outputs empty brackets.
Start with 1024. Monitor log loss (check for 'Dropped' in async appender metrics). If you see frequent drops, increase to 2048 or 4096. But consider whether you need those DEBUG/INFO events under load — sometimes dropping them is acceptable. For audit-critical logs, don't use async.
Yes. Logback supports Janino-based conditions: <if condition='property("env").equals("production")'> then set root level to WARN, else set to DEBUG. Add the logback-contrib` dependency and 'janino' library to your classpath to use conditional processing in logback.xml.
20+ years shipping production Java in banking & fintech. Everything here is grounded in real deployments.
That's Advanced Java. Mark it forged?
6 min read · try the examples if you haven't