javabeginner

Java Logging with SLF4J and Logback

Configure structured logging with SLF4J: log levels, MDC context, JSON format, and best practices.

java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class LoggingDemo {
    // One logger per class
    private static final Logger log = LoggerFactory.getLogger(LoggingDemo.class);

    public void processOrder(String orderId, String userId) {
        // Set context — appears in every log line
        MDC.put("orderId", orderId);
        MDC.put("userId", userId);

        try {
            log.info("Processing order");

            // Parameterized logging (avoids string concatenation)
            log.debug("Order details — amount: {}, items: {}", 99.99, 3);

            // Log levels
            log.trace("Detailed trace info"); // most verbose
            log.debug("Debug info for development");
            log.info("Business event: order processed");
            log.warn("Potential issue: low inventory");
            log.error("Failed to charge payment");

            // Log with exception (stack trace)
            try {
                riskyOperation();
            } catch (Exception e) {
                log.error("Operation failed for order {}", orderId, e);
                throw e;
            }

            log.info("Order completed successfully");
        } finally {
            MDC.clear(); // always clean up
        }
    }

    // Conditional expensive logging
    public void debugHeavy() {
        if (log.isDebugEnabled()) {
            // Only compute if debug is enabled
            String expensive = computeExpensiveDebugInfo();
            log.debug("Debug data: {}", expensive);
        }
    }

    // Structured data
    public void auditLog(String action, String resource) {
        MDC.put("action", action);
        MDC.put("resource", resource);
        log.info("Audit event"); // with JSON formatter: {"action":"delete","resource":"user-123"}
        MDC.remove("action");
        MDC.remove("resource");
    }

    private void riskyOperation() { /* ... */ }
    private String computeExpensiveDebugInfo() { return "data"; }
}

Use Cases

  • Application logging with contextual information
  • Structured audit logging for compliance
  • Performance-safe debug logging

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.