Coverage for src/utils/logger.py: 100%

1"""日志模块.

2

3基于 Rich 的彩色终端输出和文件日志支持。

4"""

5

6 import logging

7 from pathlib import Path

8

9 from rich.console import Console

10 from rich.logging import RichHandler

11

12

13 def get_logger(

14 name: str,

15 level: str = "INFO",

16 log_file: str | None = None,

17 console_output: bool = True,

18) -> logging.Logger:

19 """获取配置好的日志记录器.

20

21 Args:

22 name: 日志记录器名称

23 level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)

24 log_file: 日志文件路径（可选）

25 console_output: 是否输出到终端

26

27 Returns:

28 配置好的 Logger 实例

29

30 Example:

31 >>> logger = get_logger(__name__)

32 >>> logger.info("Hello, World!")

33 """

34 logger = logging.getLogger(name)

35 logger.setLevel(getattr(logging, level.upper()))

36

37 # 清除已有处理器

38 logger.handlers = []

39

40 # 终端处理器（Rich）

41 if console_output:

42 console_handler = RichHandler(

43 console=Console(stderr=True),

44 show_time=True,

45 show_path=True,

46 rich_tracebacks=True,

47 markup=True,

48 )

49 console_handler.setLevel(getattr(logging, level.upper()))

50 console_handler.setFormatter(logging.Formatter("%(message)s", datefmt="[%X]"))

51 logger.addHandler(console_handler)

52

53 # 文件处理器

54 if log_file:

55 log_path = Path(log_file)

56 log_path.parent.mkdir(parents=True, exist_ok=True)

57

58 file_handler = logging.FileHandler(log_file, encoding="utf-8")

59 file_handler.setLevel(logging.DEBUG)

60 file_formatter = logging.Formatter(

61 "%(asctime)s - %(name)s - %(levelname)s - %(message)s",

62 datefmt="%Y-%m-%d %H:%M:%S",

63 )

64 file_handler.setFormatter(file_formatter)

65 logger.addHandler(file_handler)

66

67 return logger