import logging
from logging.handlers import RotatingFileHandler

class KeywordFilter(logging.Filter):
    def __init__(self, keywords):
        super().__init__()
        self.keywords = keywords

    def filter(self, record):
        return not any(keyword in record.getMessage() for keyword in self.keywords)

class LogUtil:
    _instance = None  # 私有类变量，用于存储唯一实例

    def __new__(cls, logFilePath: str, logFormatString: str, maxBytes:int=10*1024*1024, backupCount:int=5):
        if cls._instance is None:
            cls._instance = super(LogUtil, cls).__new__(cls)
            cls._instance.init_logger(logFilePath, logFormatString)
        return cls._instance

    def init_logger(self, logFilePath: str, logFormatString: str, maxBytes:int=10*1024*1024, backupCount:int=5):
        self.logger = logging.getLogger('log')
        self.logger.setLevel(logging.DEBUG)
        
        # 设置日志格式
        formatter = logging.Formatter(logFormatString)
        
        # 创建一个旋转文件处理程序
        fileHandler = RotatingFileHandler(logFilePath, maxBytes=maxBytes, backupCount=backupCount, encoding='utf-8')
        fileHandler.setLevel(logging.DEBUG)
        fileHandler.setFormatter(formatter)
        
        # # 添加过滤器
        # keywords = ["Watching", "File"]
        # keyword_filter = KeywordFilter(keywords)
        # self.logger.addFilter(keyword_filter)
        
        # 如果没有处理程序则添加
        if not self.logger.handlers:
            self.logger.addHandler(fileHandler)

    @staticmethod
    def getLogger():
        if LogUtil._instance is None:
            raise Exception("LogUtil instance is not created yet. Please create an instance first.")
        return LogUtil._instance.logger

