_logs.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # @description:
  2. # @author: licanglong
  3. # @date: 2025/11/20 11:45
  4. import logging
  5. import sys
  6. class ColorConsoleFormatter(logging.Formatter):
  7. """
  8. 日志模块自定义输出配置
  9. 配置控制台输出的日志颜色
  10. """
  11. # ANSI 转义序列颜色代码
  12. WHITE = " \x1b[0;1m"
  13. GREY = " \x1b[37;1m"
  14. YELLOW = " \x1b[33;1m"
  15. RED = " \x1b[31;1m"
  16. GREEN = " \x1b[32;1m"
  17. BLUE = " \x1b[34;1m"
  18. RESET = " \x1b[0m"
  19. COMMON_SUFFIX = WHITE + "[{threadName:^10}]" + BLUE + "{location}:"
  20. FORMATS = {
  21. logging.DEBUG: WHITE + "{asctime}" + GREY + "{levelname:>7}" + COMMON_SUFFIX + GREY + "{message}" + RESET,
  22. logging.INFO: WHITE + "{asctime}" + GREEN + "{levelname:>7}" + COMMON_SUFFIX + WHITE + "{message}" + RESET,
  23. logging.WARNING: WHITE + "{asctime}" + YELLOW + "{levelname:>7}" + COMMON_SUFFIX + YELLOW + "{message}" + RESET,
  24. logging.WARN: WHITE + "{asctime}" + YELLOW + "{levelname:>7}" + COMMON_SUFFIX + YELLOW + "{message}" + RESET,
  25. logging.ERROR: WHITE + "{asctime}" + RED + "{levelname:>7}" + COMMON_SUFFIX + RED + "{message}" + RESET,
  26. logging.CRITICAL: WHITE + "{asctime}" + RED + "{levelname:>7}" + COMMON_SUFFIX + RED + "{message}" + RESET,
  27. }
  28. def __init__(self):
  29. super().__init__(datefmt="%Y-%m-%d %H:%M:%S")
  30. # 预创建各级别的 Formatter,避免重复实例化
  31. self._formatters = {}
  32. for level, formats in self.FORMATS.items():
  33. self._formatters[level] = logging.Formatter(formats, style="{", datefmt=self.datefmt)
  34. def format(self, record: logging.LogRecord) -> str:
  35. location = f"{record.filename}:{record.funcName}:{record.lineno}"
  36. record.location = f"{location:<40}"
  37. formatter = self._formatters.get(record.levelno, self._formatters[logging.INFO])
  38. return formatter.format(record)