import logging
import json
import datetime

class DatadogJSONFormatter(logging.Formatter):
    def format(self, record):
        # Base log object
        log_obj = {
            'timestamp': datetime.datetime.fromtimestamp(record.created).isoformat(),
            'level': record.levelname,
            'message': record.getMessage(),
            'logger': record.name,
            'module': record.module,
            'function': record.funcName,
            'line': record.lineno,
        }

        # Add Datadog trace correlation
        try:
            from ddtrace import tracer
            span = tracer.current_span()
            if span:
                log_obj['dd.trace_id'] = str(span.trace_id)
                log_obj['dd.span_id'] = str(span.span_id)
                # Datadog requires trace_id and span_id to be strings for JSON logs
        except ImportError:
            pass

        # Add ddtags if 'tags' is present in extra
        if hasattr(record, 'tags'):
            # Convert list of tags ['k:v', 'k:v'] to comma-separated string 'k:v,k:v'
            if isinstance(record.tags, list):
                log_obj['ddtags'] = ','.join(record.tags)
            else:
                log_obj['ddtags'] = str(record.tags)

        # Handle exception info
        if record.exc_info:
            log_obj['exception'] = self.formatException(record.exc_info)

        return json.dumps(log_obj)
