「Python」- 输出日志

  CREATED BY JENKINSBOT

问题描述

该笔记将记录:在 Python 中,如何进行日志打印,以及常见问题处理。

解决方案

简单示例:

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ö')

彩色日志打印:

#!/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")

参考文献

Logging HOWTO — Python 3.9.2 documentation
How can I color Python logging output? – Stack Overflow
xolox/python-coloredlogs: Colored terminal output for Python’s logging module