import logging


class LogRecordSanitizerFilter(logging.Filter):
    """
    Sanitizes Python LogRecords before OTLP export.

    1. Removes non-serializable request/response objects (Django adds these).
    2. Removes string trace_id/span_id/trace_flags set by TraceContextFilter.
       These strings leak into OTel attributes via LoggingHandler._get_attributes()
       (because they are NOT in _RESERVED_ATTRS) and can conflict with the
       integer top-level OTLP trace_id/span_id fields, causing SigNoz to
       show trace_id as "-".  The TraceContextLogProcessor re-injects the
       correct values into both attributes and the OTLP record fields.
    """

    # Attributes to strip before the OTel LoggingHandler converts the record.
    _ATTRS_TO_REMOVE = ("request", "response", "trace_id", "span_id", "trace_flags")

    def filter(self, record: logging.LogRecord) -> bool:
        for attr in self._ATTRS_TO_REMOVE:
            if hasattr(record, attr):
                try:
                    delattr(record, attr)
                except Exception:
                    pass
        return True


class NoisyLoggerFilter(logging.Filter):
    NOISY_LOGGERS = [
        "urllib3",
        "urllib3.connectionpool",
        "opentelemetry",
        "opentelemetry.sdk",
        "opentelemetry.exporter",
        "requests",
        "requests.packages.urllib3",
        "httpx",
        "botocore",
        "boto3",
    ]
    
    def filter(self, record):
        for noisy in self.NOISY_LOGGERS:
            if record.name.startswith(noisy):
                return False
        return True
