Course contentsShow
← System Design
Lesson 1142 of 1,91929. Observability: LoggingFree lesson

Logging Exceptions and Stack Traces

Properly structuring error information with stack traces, error codes, and exception types.

Logging Exceptions and Stack Traces

What you'll learn: How to structure error information in logs so you can debug failures quickly and effectively.

When something breaks in production, your logs become crime scene evidence. Just logging "an error occurred" is like a detective finding only a chalk outline—you need the full story. Exceptions and stack traces provide that story: what went wrong, where it happened, and how the code got there.

The Essential Components

When logging exceptions, capture these structured fields:

Exception type – The class name (e.g., NullPointerException, TimeoutException) tells you the category of failure.

Error message – The human-readable description from the exception itself.

Stack trace – The call chain showing exactly which line of code threw the error and how execution reached it. This is your breadcrumb trail.

Error codes – Application-specific codes that map to documentation or runbooks (e.g., ERR_DB_CONNECTION_FAILED).

Structure in JSON

{
  "level": "ERROR",
  "timestamp": "2024-01-15T10:23:45Z",
  "request_id": "abc-123",
  "error": {
    "type": "DatabaseConnectionException",
    "message": "Connection pool exhausted",
    "code": "ERR_DB_POOL_EXHAUSTED",
    "stack_trace": "com.app.db.Pool.getConnection(Pool.java:47)\n..."
  }
}

Notice the error is nested as a structured object, not concatenated into a flat string. This makes it searchable and parseable by log aggregation tools.

Practical Considerations

Include contextual fields (user ID, operation type) alongside the error—they help reproduce the issue. Keep stack traces as multi-line strings, not arrays, for readability. Always log the original exception type, even after wrapping it.

Key Takeaway: Structure exceptions as nested objects with type, message, error code, and full stack trace—this turns debugging from archaeology into engineering.