Exception Logging, Context Data, MDC, ThreadContext, and Best Practices
Make logs more useful by logging errors properly and attaching contextual information such as request ids and user ids.
Inside this chapter
- Why Exception Logging Needs Care
- Context Data and Correlation
- ThreadContext Basics
- Best Practices
Series navigation
Study the chapters in order for the clearest path from beginner logging concepts to advanced operational logging design. Use the navigation at the bottom of each page to move through the full series.
Why Exception Logging Needs Care
Logging an exception is not just about printing the exception message. Good logging captures stack traces, business context, operation intent, and enough detail to help support teams reproduce or diagnose the issue without exposing sensitive data unnecessarily.
try {
processPayment();
} catch (Exception ex) {
logger.error("Payment processing failed for orderId={}", orderId, ex);
} Context Data and Correlation
Contextual data such as request id, customer id, tenant id, session id, or batch job id makes logs dramatically more useful. Without context, even correctly logged errors can be hard to trace across distributed systems.
ThreadContext Basics
ThreadContext.put("requestId", requestId);
ThreadContext.put("userId", userId);
logger.info("User profile loaded");
ThreadContext lets you enrich logs with metadata that can be included in layouts automatically.
Best Practices
- Include enough context to debug the issue
- Do not log secrets, passwords, or sensitive payloads casually
- Log exceptions once at the right boundary instead of duplicating noise
- Use correlation ids in request-driven systems