python_日志记录-loguru

1 使用 loguru

安装

pip install loguru

如何使用

from loguru import logger

logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")

这里的输出包含颜色:

2025-06-27 02:35:10.391 | DEBUG | __main__:<cell line: 0>:3 - This is a debug message 
2025-06-27 02:35:10.394 | INFO | __main__:<cell line: 0>:4 - This is an info message 
2025-06-27 02:35:10.396 | WARNING | __main__:<cell line: 0>:5 - This is a warning message 
2025-06-27 02:35:10.397 | ERROR | __main__:<cell line: 0>:6 - This is an error message 
2025-06-27 02:35:10.399 | CRITICAL | __main__:<cell line: 0>:7 - This is a critical message

写入文件

from loguru import logger

logger.add("file.log", rotation="100 MB")  # 自动将日志写入文件,当文件大小超过 100MB 时,会自动新建一个文件
logger.info("This log will be written to file.log")

rotation 参数可以设置文件大小或时间间隔,例如:

  • rotation="100 MB":当文件大小超过 100MB 时,新建文件。
  • rotation="1 week":每周新建一个文件。
  • rotation="100 MB / 1 week":当文件大小超过 100MB 或时间超过一周时,新建文件。
posted @ 2025-10-21 19:12  solarlemon  阅读(2)  评论(0)    收藏  举报