Skip to content
beginnerPhase ·

Logging

Implement proper logging in backend applications.

35m
0 problems
Topic Progress0%

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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement Logging

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
}
Logging Edge Cases

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, idempotency
Logging Testing Strategy

Write 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 injection

Quiz

1. Which log level should be used for errors that need immediate attention?

Question 1 options

2. What is the benefit of using parameterized log messages?

Question 2 options

3. What is the primary purpose of Logging?

Question 3 options

4. What is a common mistake when implementing Logging?

Question 4 options

Flashcards

Question

What log levels exist in order?

Answer

TRACE, DEBUG, INFO, WARN, ERROR (least to most severe)

Question

What is MDC?

Answer

Mapped Diagnostic Context — adds requestId, userId etc. to all logs in a thread

Question

What is Logging?

Answer

Logging is a key concept in backend development.

Question

When to use Logging?

Answer

Use Logging when building production systems that require reliability, scalability, and maintainability.

Question

Logging best practices

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)