Logging in Spring Boot
Logging is essential for debugging, monitoring, and auditing backend applications.
SLF4J + Logback (Spring Boot Default)
Spring Boot uses SLF4J as the logging facade and Logback as the implementation:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Service
public class ProductService {
private static final Logger log = LoggerFactory.getLogger(ProductService.class);
public ProductDto getProduct(Long id) {
log.debug("Fetching product with id: {}", id);
Product product = productRepository.findById(id)
.orElseThrow(() -> {
log.warn("Product not found with id: {}", id);
return new ResourceNotFoundException("Product not found");
});
log.info("Successfully retrieved product: {}", product.getName());
return productMapper.toDto(product);
}
}
Log Levels
| Level | When to Use |
|---|---|
ERROR |
Something failed — needs immediate attention |
WARN |
Something unexpected — not critical |
INFO |
Key business events — order placed, user logged in |
DEBUG |
Detailed info for debugging — method entry/exit |
TRACE |
Very detailed — variable values, flow control |
Configuration (application.yml)
logging:
level:
root: INFO
com.example: DEBUG
com.example.repository: WARN
Logging Best Practices
Levels
TRACE < DEBUG < INFO < WARN < ERROR < FATAL
Structured Logging
{
"timestamp": "...",
"level": "INFO",
"message": "...",
"requestId": "..."
}
Best Practices
- Use SLF4J facade
- Include correlation IDs
- Don't log sensitive data
- Use appropriate levels
Key Points
- Understanding Logging is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Logging in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Logging implementation
// Key aspects: validation, error handling, logging, testing
public class Logging {
// Production-ready implementation
}Identify and handle edge cases for Logging. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Logging. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. Which log level should be used for errors that need immediate attention?
2. What is the benefit of using parameterized log messages?
3. What is the primary purpose of Logging?
4. What is a common mistake when implementing Logging?
Flashcards
Question
What log levels exist in order?
Click to reveal answer
Answer
TRACE, DEBUG, INFO, WARN, ERROR (least to most severe)
Question
What is MDC?
Click to reveal answer
Answer
Mapped Diagnostic Context — adds requestId, userId etc. to all logs in a thread
Question
What is Logging?
Click to reveal answer
Answer
Logging is a key concept in backend development.
Question
When to use Logging?
Click to reveal answer
Answer
Use Logging when building production systems that require reliability, scalability, and maintainability.
Question
Logging best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Log levels from least to most severe: TRACE, DEBUG, INFO, WARN, ERROR
- 2.Use SLF4J Logger with LoggerFactory.getLogger(ClassName.class)
- 3.Spring Boot defaults to Logback with sensible configuration
- 4.Configure log levels per package in application.yml for fine-grained control
- 5.MDC (Mapped Diagnostic Context) adds requestId, userId to all logs in a thread
Interview Tips
- •Know when to use each log level (ERROR for failures, WARN for unexpected, INFO for business events, DEBUG for troubleshooting)
- •Explain how to configure different log levels for different packages
- •Discuss structured logging and its benefits for production monitoring
Cheat Sheet
Logging
- Log levels: TRACE < DEBUG < INFO < WARN < ERROR
- Logger: private static final Logger log = LoggerFactory.getLogger(ClassName.class)
- Spring Boot uses SLF4J + Logback
- Configure in application.yml:
logging.level.root: INFO
logging.level.com.example: DEBUG - MDC: add context (requestId, userId) to all logs in thread
- Use parameterized messages: log.info("User {} logged in", username)