feat(log): add trace_id/span_id to JSON log records inside a span

GA
7h ago
+111-0

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update (included)

Description

Closes #6903.

When OpenTelemetry tracing is enabled, JsonHandler.emit (reflex_base/utils/log.py) now adds the current span's W3C trace_id (32 hex) and span_id (16 hex) to each JSON log record, so a log line can be looked up in the tracing UI and vice versa.

  • reflex_base.otel.trace_fields() (new) returns {"trace_id", "span_id"} for the current valid span, or None when tracing is off or no valid span is current. It uses the trace module that enable() binds, so it has no import statement, and with tracing off nothing from opentelemetry is imported (test_disabled_path_imports_no_opentelemetry still passes). I added it to the "trace points carry no import statement" test as well, since it runs once per log record.
  • JsonHandler.emit merges those fields into the payload. Records emitted outside a span, or with tracing off, are unchanged.
  • reflex_otel was already in PACKAGE_LOGGER_NAMES on main, so this PR doesn't touch that part of the issue.
  • Docs: added a "Logs" section to docs/api-reference/observability.md.
  • News fragment: packages/reflex-base/news/+json-log-trace-ids.feature.md.

I left the optional rich console/file formatter change out to keep this PR small.

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Tests:

  • tests/units/reflex_base/utils/test_log.py: test_json_mode_adds_trace_ids (info and error records inside a span carry exactly that span's ids; this fails on main with KeyError: 'trace_id'), test_json_mode_omits_trace_ids_outside_span, test_json_mode_omits_trace_ids_when_tracing_disabled.
  • tests/units/reflex_base/test_otel.py: trace_fields() when disabled, when enabled with no current span, and inside a span.

Local results: uv run pytest tests/units --cov passes except 3 tests that also fail on main in my environment (two dataeditor tests need node, and one bench HMR test). ruff check, ruff format --check, and the pre-commit hooks (pyright, ty, codespell) pass on the changed files.


🤖 Opened with Superhuman, an open-source contribution agent.