安装 coloredlogs
pip install coloredlogs
使用
首先,和正常打印日志一样,我们创建一个 logger
logging.basicConfig()
logger = logging.getLogger(name='mylogger')
然后,把 logger 安装到 coloredlogs:
coloredlogs.install(logger=logger)
logger.propagate = False
logger.propagate = False 确保 coloredlogs 不会将我们的日志事件传递给根 logger,这可以防止我们重复记录每个事件。
我们想为我们的控制台输出添加一些样式,可以在这里定义:
coloredFormatter = coloredlogs.ColoredFormatter(
fmt='[%(name)s] %(asctime)s %(funcName)s %(lineno)-3d %(message)s',
level_styles=dict(
debug=dict(color='white'),
info=dict(color='blue'),
warning=dict(color='yellow', bright=True),
error=dict(color='red', bold=True, bright=True),
critical=dict(color='black', bold=True, background='red'),
),
field_styles=dict(
name=dict(color='white'),
asctime=dict(color='white'),
funcName=dict(color='white'),
lineno=dict(color='white'),
)
)
接下来就和正常使用日志一样了,配置一个流处理器,让日志显示在控制台:
ch = logging.StreamHandler(stream=sys.stdout)
ch.setFormatter(fmt=coloredFormatter)
logger.addHandler(hdlr=ch)
logger.setLevel(level=logging.DEBUG)
接下来就可以输入日志信息了:
logger.debug(msg="this is a debug message")
logger.info(msg="this is an info message")
logger.warning(msg="this is a warning message")
logger.error(msg="this is an error message")
logger.critical(msg="this is a critical message")
效果图如下:
完整代码如下:
import logging
import coloredlogs
import sys
## 配置 logger
logging.basicConfig()
logger = logging.getLogger(name='mylogger')
coloredlogs.install(logger=logger)
logger.propagate = False
## 配置 颜色
coloredFormatter = coloredlogs.ColoredFormatter(
fmt='[%(name)s] %(asctime)s %(funcName)s %(lineno)-3d %(message)s',
level_styles=dict(
debug=dict(color='white'),
info=dict(color='blue'),
warning=dict(color='yellow', bright=True),
error=dict(color='red', bold=True, bright=True),
critical=dict(color='black', bold=True, background='red'),
),
field_styles=dict(
name=dict(color='white'),
asctime=dict(color='white'),
funcName=dict(color='white'),
lineno=dict(color='white'),
)
)
## 配置 StreamHandler
ch = logging.StreamHandler(stream=sys.stdout)
ch.setFormatter(fmt=coloredFormatter)
logger.addHandler(hdlr=ch)
logger.setLevel(level=logging.DEBUG)
## output
logger.debug(msg="this is a debug message")
logger.info(msg="this is an info message")
logger.warning(msg="this is a warning message")
logger.error(msg="this is an error message")
logger.critical(msg="this is a critical message")