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

Contextual Fields

Adding request-specific context like user_id, request_id, and session_id to every log entry.

Contextual Fields

What You'll Learn

You'll learn how to enrich every log entry with request-specific context like user_id, request_id, and session_id to make debugging and troubleshooting dramatically easier.

The Core Idea

Contextual fields are additional key-value pairs you add to structured logs that describe who, what, and where for each request. Instead of logging a generic message like "Payment processed," you log that message plus user_id: 12345, request_id: abc-789, and session_id: xyz-456. This context travels with every log entry throughout the request lifecycle.

Think of it like a detective's case file. A note saying "suspect interviewed" isn't very useful. But "suspect interviewed — Case #4567, Detective Smith, Location: 123 Main St" gives you everything you need to reconstruct what happened.

Why Contextual Fields Matter

When troubleshooting production issues, you need to:

  • Filter all logs for a specific user to see their entire journey
  • Track a single request across multiple services
  • Group related operations from the same session

Without contextual fields, your logs are disconnected events. With them, you can instantly find "all logs for user 12345 in the last hour" or "trace request abc-789 from gateway to database."

Common Contextual Fields

  • request_id — unique identifier for this request
  • user_id — which user triggered this action
  • session_id — browser or API session identifier
  • service_name — which microservice generated the log
  • environment — production, staging, or dev

These fields appear in every log entry, making correlation trivial.

Key Takeaway: Contextual fields transform logs from isolated messages into connected stories by adding request-specific metadata to every entry, enabling powerful filtering and correlation during debugging.