import logging


class LogRecordSanitizerFilter(logging.Filter):
    """
    Removes request/response objects from log records before OTLP export.
    OpenTelemetry attributes must be primitive types (bool, str, int, float, bytes).
    Django's request_logging adds Response/HttpRequest objects which cause:
    "Invalid type Response for attribute 'response' value"
    """

    def filter(self, record: logging.LogRecord) -> bool:
        # Remove non-serializable attributes (keep response_status, response_str, etc.)
        for attr in ("request", "response"):
            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
