logUtil.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import logging
  2. from logging.handlers import RotatingFileHandler
  3. class KeywordFilter(logging.Filter):
  4. def __init__(self, keywords):
  5. super().__init__()
  6. self.keywords = keywords
  7. def filter(self, record):
  8. return not any(keyword in record.getMessage() for keyword in self.keywords)
  9. class LogUtil:
  10. _instance = None # 私有类变量,用于存储唯一实例
  11. def __new__(cls, logFilePath: str, logFormatString: str, maxBytes:int=10*1024*1024, backupCount:int=5):
  12. if cls._instance is None:
  13. cls._instance = super(LogUtil, cls).__new__(cls)
  14. cls._instance.init_logger(logFilePath, logFormatString)
  15. return cls._instance
  16. def init_logger(self, logFilePath: str, logFormatString: str, maxBytes:int=10*1024*1024, backupCount:int=5):
  17. self.logger = logging.getLogger('log')
  18. self.logger.setLevel(logging.DEBUG)
  19. # 设置日志格式
  20. formatter = logging.Formatter(logFormatString)
  21. # 创建一个旋转文件处理程序
  22. fileHandler = RotatingFileHandler(logFilePath, maxBytes=maxBytes, backupCount=backupCount, encoding='utf-8')
  23. fileHandler.setLevel(logging.DEBUG)
  24. fileHandler.setFormatter(formatter)
  25. # # 添加过滤器
  26. # keywords = ["Watching", "File"]
  27. # keyword_filter = KeywordFilter(keywords)
  28. # self.logger.addFilter(keyword_filter)
  29. # 如果没有处理程序则添加
  30. if not self.logger.handlers:
  31. self.logger.addHandler(fileHandler)
  32. @staticmethod
  33. def getLogger():
  34. if LogUtil._instance is None:
  35. raise Exception("LogUtil instance is not created yet. Please create an instance first.")
  36. return LogUtil._instance.logger