Sub topic 3
Configuring Logback
Assume basic Java, Maven or Gradle dependency management, and try/catch. Logback is a logging backend: it decides where messages go and how they are formatted. SLF4J is the API that application code calls.
Configure Logback
Add the SLF4J API and Logback provider. The application compiles against the API, while Logback supplies the runtime implementation.
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.16</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.12</version>
<scope>runtime</scope>
</dependency>
</dependencies>Put logback.xml on the classpath, usually in src/main/resources:
<configuration>
<appender name="CONSOLE"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level [%thread] %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<logger name="com.example.payments" level="DEBUG"/>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>The root level applies by default. The package-specific logger enables DEBUG only for that package.
Add request context with MDC
MDC, or mapped diagnostic context, stores key-value data for the current thread. Add %X{requestId} to the pattern and clear the value after handling the request.
try (MDC.MDCCloseable ignored =
MDC.putCloseable("requestId", requestId)) {
log.info("Handling request");
}Use key-value pairs
SLF4J 2.x supports structured fields through its fluent API:
log.atInfo()
.addKeyValue("orderId", 42)
.addKeyValue("status", "SHIPPED")
.log("Order status changed");The encoder or log collector must support these fields for them to appear as structured output.
Route System.Logger into SLF4J
Add slf4j-jdk-platform-logging at runtime. It registers a System.LoggerFinder, forwarding JDK and library messages to SLF4J and therefore to Logback.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk-platform-logging</artifactId>
<version>2.0.16</version>
<scope>runtime</scope>
</dependency>Choose an API and avoid common errors
Use System.Logger when you want a JDK-only dependency. Use SLF4J when your application needs a broad ecosystem and configurable providers. Use parameterized messages or suppliers so disabled log levels do not perform unnecessary formatting. Select levels consistently: DEBUG for diagnostics, INFO for important normal events, WARNING for recoverable problems, and ERROR for failures. Do not log secrets, and ensure exactly one SLF4J provider is present.
Exercise
What should you check when SLF4J reports that no provider was found?
Show answer
Add one runtime provider, such as logback-classic, and check that dependency conflicts have not removed or replaced it.