from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
import sys
class AIGCLog:
    def __init__(self, name="系统", log_file = "system.log"):
        """
        初始化日志系统
        :param name: 日志记录器名称（显示在日志中的模块名）
        :param log_file: 日志文件路径
        """
        self.logger = logging.getLogger(name)
        self.logger.propagate = False
        self.logger.setLevel(logging.DEBUG)
        if not self.logger.handlers:
            self.logger.handlers.clear()  # 清除现有处理器
            formatter = self._create_custom_formatter()
            console_handler = self._create_console_handler(formatter)
            file_handler = self._create_file_handler(log_file, formatter)

            self.logger.addHandler(console_handler)
            self.logger.addHandler(file_handler)

    def _create_custom_formatter(self):
        #创建自定义的日志格式
        class AITimeFormatter(logging.Formatter):
            def formatTime(self, record, datefmt=None):
                ct = datetime.fromtimestamp(record.created)
                tenth_second = int(record.msecs / 100)
                return f"{ct:%Y-%m-%d %H:%M:%S}, {tenth_second}"

        return AITimeFormatter(
            fmt='[%(asctime)s][%(name)s] %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')

    def _create_console_handler(self, formatter):
        #控制台输出
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(formatter)
        return console_handler

    def _create_file_handler(self, log_file, formatter):
        #创建文件处理爱
        file_handler = TimedRotatingFileHandler(
            filename=log_file,
            when='midnight',
            interval=1,
            backupCount=7,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
        return file_handler
    
    def log(self, level, msg):
        if level == logging.DEBUG:
            self.logger.debug(msg)
        elif level == logging.INFO:
            self.logger.info(msg)
        elif level == logging.WARNING:
            self.logger.warning(msg)
        elif level == logging.ERROR:
            self.logger.error(msg)
        elif level == logging.CRITICAL:
            self.logger.critical(msg)
        else:
            self.logger.info(msg)  # 默认使用INFO级别

if __name__ == "__main__":
    #初始化日志系统
    logger = AIGCLog(name = "系统log", log_file = "system.log")
