该笔记将记录:在 Python 中,如何进行日志打印,以及常见问题处理。
认识
文档:https://docs.python.org/3/library/logging.html
构建
logging 属于 The Python Standard Library,所以不需要单独安装。
应用
Logging HOWTO — Python 3.9.2 documentation
import logging
logging.basicConfig(encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
格式化输出内容
LogRecord attributes | https://docs.python.org/3/library/logging.html#logrecord-attributes
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s')
# 固定字段宽度
# https://stackoverflow.com/questions/47035760/python-truncated-logging-level-names-string-formatting-customization
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s | %(levelname).3s | %(message)s')
logging.debug('This message should go to the log file')
2025-03-05 19:35:16,473 | DEB | This message should go to the log file
彩色日志打印
How can I color Python logging output? – Stack Overflow
xolox/python-coloredlogs: Colored terminal output for Python’s logging module
通过模块实现
#!/usr/bin/python3
# pip install coloredlogs
# 简单示例
import coloredlogs, logging
coloredlogs.install()
logging.info("It works!") # 2014-07-30 21:21:26 peter-macbook root[7471] INFO It works!
# 特定 Logger 设置
logger = logging.getLogger(__name__)
coloredlogs.install(level='DEBUG', logger=logger) # a specific logger object
logger.debug("this is a debugging message")
logger.info("this is an informational message")
logger.warning("this is a warning message")
logger.error("this is an error message")
logger.critical("this is a critical message")
通过自定义类
https://stackoverflow.com/questions/384076/how-can-i-color-python-logging-output