"""
Logging filter that injects OpenTelemetry trace context (trace_id, span_id) into log records.
Enables log-trace correlation in SigNoz and other backends.
"""
import logging

from opentelemetry import trace


class TraceContextFilter(logging.Filter):
    """
    Adds trace_id and span_id to log records from the current OpenTelemetry span context.
    Use with Django LOGGING config: {"()": "varicon_observability.trace_filter.TraceContextFilter"}
    """

    def filter(self, record: logging.LogRecord) -> bool:
        span = trace.get_current_span()
        ctx = span.get_span_context()
        if ctx.is_valid:
            record.trace_id = format(ctx.trace_id, "032x")
            record.span_id = format(ctx.span_id, "016x")
        else:
            record.trace_id = ""
            record.span_id = ""
        return True
