Skip to content

Create a custom logging.Filter that automatically extracts the current OpenTelemetry trace context and injects trace_id and span_id into every log record #458

@psschwei

Description

@psschwei

Description:
Create a custom logging.Filter that automatically extracts the current OpenTelemetry trace context and injects trace_id and span_id into every log record. This enables correlation between logs and distributed traces.

Detailed Requirements:

  1. Create OtelTraceFilter class (extends logging.Filter) that:
    • Gets current span from opentelemetry.trace.get_current_span()
    • Extracts trace_id and span_id from span context
    • Adds fields to LogRecord as attributes
    • Handles case when no active span (sets to None or empty string)
  2. Add filter to FancyLogger's handlers
  3. Update JsonFormatter to include trace_id/span_id fields
  4. Update CustomFormatter to optionally show trace context
  5. Ensure zero overhead when OpenTelemetry not installed (graceful degradation)
  6. Format trace_id/span_id as hex strings (standard OTEL format)

Files to Modify:

  • mellea/core/utils.py - Add OtelTraceFilter, update formatters

Acceptance Criteria:

  • trace_id and span_id appear in all JSON log records when tracing is active
  • Logs work correctly when tracing is disabled (fields are null/absent)
  • No import errors when opentelemetry not installed
  • Filter added to FancyLogger initialization

Metadata

Metadata

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions