Context & Scope

Attach user info, tags, and breadcrumbs to events using contextvars.

Context helps you answer who hit a bug and what happened right before it.

What it does

TraceKit stores scope in Python contextvars using copy-on-write updates:

  • tracekit.set_user(id=..., **fields) attaches a user object to subsequent events.
  • tracekit.set_tag(key, value) attaches string key/value tags.
  • tracekit.add_breadcrumb(message, category=None) records up to 20 recent trail items (oldest are dropped).

Because contextvars are isolated per thread and per asyncio task, setting a user in one request never bleeds into another.

Minimal example

scope_demo.py
import tracekit
tracekit.init(output="file:events.jsonl", environment="production")
tracekit.set_user(id="42", email="alice@example.com")tracekit.set_tag("region", "us-east-1")tracekit.add_breadcrumb("Loaded cart", category="checkout")
try:    raise RuntimeError("Payment gateway timeout")except RuntimeError:    tracekit.capture_exception()
tracekit.flush()

Expected output

In events.jsonl, the recorded error event includes user, tags, and breadcrumbs:

events.jsonl
{  "type": "error",  "user": { "id": "42", "email": "alice@example.com" },  "tags": { "region": "us-east-1" },  "breadcrumbs": [    {      "ts": "2026-11-28T09:56:10.371Z",      "message": "Loaded cart",      "category": "checkout"    }  ]}

If a scope field is empty, it is omitted from the event JSON rather than set to null.

Common mistakes

  • Expecting more than 20 breadcrumbs: TraceKit keeps the newest 20 breadcrumbs per context to bound memory usage.
  • Passing non-string values to set_tag: set_tag(key, value) expects string values (str).