Integrate structlog with tenant_id and request_id context on every request #15

Open
opened 2026-04-20 09:36:28 +00:00 by sharang · 0 comments
Owner

Problem

main.py uses logging.basicConfig() with a plain text format. Logs contain no tenant_id, user_id, or request_id. Correlating a user-reported problem with a log entry is impossible.

Required Actions

  1. Add structlog to requirements.txt
  2. Configure structlog with JSON renderer in production, console renderer in dev
  3. Add a FastAPI middleware that generates a request_id (UUID) per request and binds tenant_id, user_id, request_id, method, path to the structlog context via structlog.contextvars.bind_contextvars()
  4. Replace all logging.getLogger(__name__) calls with structlog.get_logger()
  5. Ensure every log line in a request handler automatically includes the bound context

Acceptance Criteria

  • Every log line emitted during a request includes tenant_id, request_id
  • Logs are valid JSON in production (LOG_FORMAT=json)
  • grep tenant_id on any request log returns the correct tenant
## Problem `main.py` uses `logging.basicConfig()` with a plain text format. Logs contain no `tenant_id`, `user_id`, or `request_id`. Correlating a user-reported problem with a log entry is impossible. ## Required Actions 1. Add `structlog` to `requirements.txt` 2. Configure structlog with JSON renderer in production, console renderer in dev 3. Add a FastAPI middleware that generates a `request_id` (UUID) per request and binds `tenant_id`, `user_id`, `request_id`, `method`, `path` to the structlog context via `structlog.contextvars.bind_contextvars()` 4. Replace all `logging.getLogger(__name__)` calls with `structlog.get_logger()` 5. Ensure every log line in a request handler automatically includes the bound context ## Acceptance Criteria - Every log line emitted during a request includes `tenant_id`, `request_id` - Logs are valid JSON in production (`LOG_FORMAT=json`) - `grep tenant_id` on any request log returns the correct tenant
sharang added this to the M3: Observability & Audit Logging milestone 2026-04-20 09:36:28 +00:00
sharang added the observabilityseverity: medium labels 2026-04-20 09:36:28 +00:00
Sign in to join this conversation.