4.5. Logging
4.5.1. Logging Framework
- SLF4J + Logback must be used. (Provided by default in Spring Boot)
System.out.println()must not be used for logging purposes.
4.5.2. Log Level Policy
| Level | Usage Criteria |
|---|---|
ERROR | System failures requiring immediate response |
WARN | Potential issues; abnormal but service remains operational |
INFO | Major business events, application state changes |
DEBUG | Debugging information during development (disabled in production) |
TRACE | Detailed flow tracing (disabled in production) |
4.5.3. Log Writing Rules
- Declare a logger per class.
java
private static final Logger log = LoggerFactory.getLogger(UserService.class);- Alternatively, use the Lombok
@Slf4jannotation. - Use parameter binding in log messages.
java
// Bad
log.info("User created: " + userId);
// Good
log.info("User created: userId={}", userId);- Include the stack trace when logging exceptions.
java
log.error("User lookup failed: userId={}", userId, exception);4.5.4. Production Log Format
xml
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>