---
title: Log All Relevant Context On Errors
impact: HIGH
impactDescription: enables quick debugging and accurate incident response
tags: error-handling, logging, context, debugging, quality, kotlin
---

## Log All Relevant Context On Errors

Logs without context are nearly useless for production troubleshooting. Comprehensive context-rich logs allow developers to reconstruct the state that led to an error.

**Incorrect (minimal context):**

```kotlin
logger.error("Error occurred")
logger.error(exception.message)
```

**Correct (comprehensive context):**

```kotlin
logger.error("Failed to process order", exception) {
    // What happened
    payload("errorCode" to exception.code)
    
    // Core Business Context
    payload("orderId" to order.id)
    payload("userId" to user.id)
    payload("requestId" to MDC.get("requestId")) // Assuming MDC use
    
    // Input/State that caused the issue
    payload("itemsCount" to order.items.size)
    payload("totalAmount" to order.total)
    
    // Timing information
    payload("processingTimeMs" to System.currentTimeMillis() - startTime)
}
```

**Essential log context should include:**
- Error details (Exception name, full stack trace).
- Entity IDs (user ID, order ID, account ID).
- Coordination IDs (Request ID, Correlation ID, Trace ID).
- Summarized input data (avoid PII - Personal Identifiable Information).
- System state hints (environment, version).

**Tools:** SLF4J with Logback/Log4j2, Structured Logging (KLogging, Logstash Logback Encoder), Sentry
