import json
import logging


class JsonLoggingFormatter(logging.Formatter):

    _default_level = "INFO"
    _levels_map = {
        logging.DEBUG: "DEBUG",
        logging.INFO: "INFO",
        logging.WARNING: "WARNING",
        logging.ERROR: "ERROR",
        logging.CRITICAL: "ERROR",  # qloud has no CRITICAL
    }

    def format(self, record: logging.LogRecord) -> str:
        data = {
            "msg": record.getMessage(),
            "level": self._levels_map.get(record.levelno, self._default_level),
        }

        if record.exc_info is not None:
            data["stackTrace"] = record.exc_info[2]

        extra_fields = getattr(record, "fields", None)
        if isinstance(extra_fields, dict):
            data["@fields"] = extra_fields

        return json.dumps(data)
