前段时间,我看到一个带有彩色输出的Mono应用程序,可能是因为它的日志系统(因为所有的消息都是标准化的).
现在,Python有了这个logging模块,它允许你指定很多选项来自定义输出.所以,我想象Python可能会有类似的东西,但我无法在任何地方找到如何做到这一点.
有没有办法让Python logging模块输出颜色?
我想要的(例如)红色错误,蓝色或黄色调试消息,等等.
当然这可能需要一个兼容的终端(大多数现代终端); 但logging如果不支持颜色,我可以回退到原始输出.
有关如何使用记录模块获得彩色输出的任何想法?
我在这里问了python 2的这个问题,但是当Python 3.2.3的答案不再有效时再次遇到了问题.
这里的代码适用于Python 2.7.3:
import logging
# Attempt to set up a Python3 logger than will print custom messages
# based on each message's logging level.
# The technique recommended for Python2 does not appear to work for
# Python3
class CustomConsoleFormatter(logging.Formatter):
"""
Modify the way DEBUG messages are displayed.
"""
def __init__(self, fmt="%(levelno)d: %(msg)s"):
logging.Formatter.__init__(self, fmt=fmt)
def format(self, record):
# Remember the original format
format_orig = self._fmt
if record.levelno == logging.DEBUG:
self._fmt = "DEBUG: %(msg)s"
# …Run Code Online (Sandbox Code Playgroud)