Sub topic 3
Different Logging for Dev and Prod Profiles
Assume you know basic Java, Spring Boot configuration, and Spring profiles. This chapter focuses on choosing useful output for each environment without changing application code.
Profile-specific logging
Use logback-spring.xml when logging depends on an active Spring profile. Spring Boot can read <springProfile> and apply different appenders or levels.
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<springProfile name="dev">
<root level="DEBUG">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
<springProfile name="prod">
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
</configuration>Development can show detailed diagnostics. Production should usually reduce noise and avoid exposing sensitive values.
Request context with MDC
MDC, or mapped diagnostic context, stores values for the current request thread. Put a request ID into MDC in a filter, include %X{requestId} in the pattern, and remove it in finally.
MDC.put("requestId", UUID.randomUUID().toString());
try {
chain.doFilter(request, response);
} finally {
MDC.remove("requestId");
}The cleanup is essential because servlet threads are reused.
Structured logging
Log aggregation tools search fields more reliably than plain text. In Spring Boot 3.4 and later, ECS JSON output can be enabled with:
logging.structured.format.console=ecsRuntime level changes
Actuator can expose the loggers endpoint. A POST changes one logger without restarting the application:
curl -X POST http://localhost:8080/actuator/loggers/com.example.orders \
-H 'Content-Type: application/json' \
-d '{"configuredLevel":"DEBUG"}'Protect this endpoint. Do not expose it publicly without authentication and authorization.
Switching to Log4j2
Spring Boot uses Logback by default. To switch backends, exclude spring-boot-starter-logging and add spring-boot-starter-log4j2. Choose Log4j2 when its plugins, appenders, or existing operational standards justify the migration.
Testing and pitfalls
Use Spring Boot’s OutputCaptureExtension to assert that important messages appear. Test meaningful levels and exception output, not exact timestamps.
Keep messages actionable. Use INFO for important business events, DEBUG for diagnostics, WARN for recoverable problems, and ERROR for failed operations. Add request IDs consistently, rotate files when using file output, and avoid logging the same exception at every layer.
Exercise
Why must an MDC request ID be removed after processing?
Show answer
Servlet threads are reused, so removal prevents one request’s ID from appearing in another request’s logs.