import logging
import sys
import os

TRACE = 5
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
NOTSET = logging.NOTSET

def get_logger(name=None):
    if name is None:
        name = 'alkaid_release_platform'
    # 创建一个 logger
    logger = logging.getLogger(name)
    if logger.handlers:
        return logger

    #定义一个新的日志级别，用于输出trace信息
    logging.TRACE = TRACE
    logging.addLevelName(logging.TRACE, "TRACE")
    def trace(self, message, *args, **kws):
        self._log(logging.TRACE, message, args, **kws)
    logging.Logger.trace = trace

    logger.setLevel(INFO)
    class LogColors:
        RESET = "\033[0m"
        TRACE = "\033[35m" # 紫色
        DEBUG = "\033[34m"  # 蓝色
        INFO = "\033[32m"   # 绿色
        WARNING = "\033[33m" # 黄色
        ERROR = "\033[31m"   # 红色
        CRITICAL = "\033[41m" # 红底白字

    # 创建一个log的颜色格式化器，使得输出的log信息在控制台上有颜色区分
    class ColoredFormatter(logging.Formatter):
        def __init__(self, msg, use_color=True):
            logging.Formatter.__init__(self, msg)
            self.use_color = use_color
        def format(self, record):
            level_color = {
                logging.TRACE: LogColors.TRACE,
                logging.DEBUG: LogColors.DEBUG,
                logging.INFO: LogColors.INFO,
                logging.WARNING: LogColors.WARNING,
                logging.ERROR: LogColors.ERROR,
                logging.CRITICAL: LogColors.CRITICAL
            }
            color = level_color.get(record.levelno, LogColors.RESET)
            message = super().format(record)
            return f"{color}{message}{LogColors.RESET}" if os.isatty(sys.stdout.fileno()) else message

    # 创建一个带颜色的控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(INFO)
    # 创建一个带颜色的格式化器并将其添加到处理器
    formatter = ColoredFormatter('[%(asctime)s][%(levelname)s][%(filename)s:%(lineno)d]: %(message)s')
    console_handler.setFormatter(formatter)

    # 将处理器添加到 logger
    logger.addHandler(console_handler)

    # 定义一个方法，用于设置日志级别，并将其绑定到 logger 对象
    def set_level(self, level):
        lv_map = {
            "trace":TRACE,
            "debug":DEBUG,
            "info":INFO,
            "warning":WARNING,
            "error":ERROR,
            "critical":CRITICAL
        }
        level = lv_map.get(level, DEBUG)
        for handler in self.handlers:
            handler.setLevel(level)
        logger.setLevel(level)
    logging.Logger.set_level = set_level
    return logger

