添加新的彩色级别日志记录

Add a new colored level logging

所以这段代码输出带有颜色的关卡名称(默认关卡),我想添加我自己的额外关卡,然后给它们自定义颜色。

代码:

import logging
import re
import time
import sys

def set_colour(level):
    """
    Sets colour of text for the level name in
    logging statements using a dispatcher.
    """
    escaped = "[3[1;%sm%s3[1;0m]"
    return {
        'INFO': lambda: logging.addLevelName(logging.INFO, escaped % ('94', level)),
        'WARNING': lambda: logging.addLevelName(logging.ERROR, escaped % ('93', level)),
        'ERROR': lambda: logging.addLevelName(logging.WARNING, escaped % ('91', level))
    }.get(level, lambda: None)()


class NoColorFormatter(logging.Formatter):
    """
    Log formatter that strips terminal colour
    escape codes from the log message.
    """

    # Regex for ANSI colour codes
    ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")

    def format(self, record):
        """Return logger message with terminal escapes removed."""
        return "%s %s %s" % (
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            re.sub(self.ANSI_RE, "", record.levelname),
            record.msg,
        )

# Create logger
logger = logging.getLogger(__package__)

# Create formatters
logformatter = NoColorFormatter()
colorformatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")

# Set logging colours
for level in 'INFO', 'ERROR', 'WARNING':
    set_colour(level)

# Set logging level
logger.setLevel(logging.INFO)

# Set log handlers
loghandler = logging.FileHandler("log.txt", mode="a", encoding="utf8")
streamhandler = logging.StreamHandler(sys.stdout)

# Set log formatters
loghandler.setFormatter(logformatter)
streamhandler.setFormatter(colorformatter)

# Attach log handlers to logger
logger.addHandler(loghandler)
logger.addHandler(streamhandler)

# Example logging statements
logging.info("This is just an information for you")
logging.warning("This is just a warning for you")
logging.error("This is just an error for you")

我要完成的是一个新的关卡,但有其独特的颜色。

这是我如何完成添加新关卡的代码:

def success(msg, *args, **kwargs):
    if logging.getLogger().isEnabledFor(70):
        logging.log(70, msg)

logging.addLevelName(70, "SUCCESS")
logging.success = success
logging.Logger.success = success

以上代码正常运行但不包含任何颜色。如何添加此代码以获得新级别,但颜色不同?

这需要添加几行,包括此块(添加另一行来设置 logging.SUCCESS 的整数值:

def success(msg, *args, **kwargs):
    if logging.getLogger().isEnabledFor(70):
        logging.log(70, msg)

logging.addLevelName(70, "SUCCESS")
logging.SUCCESS = 70   # similar to logging.INFO -> 20
logging.success = success
logging.Logger.success = success

我已经在此处指出 added/modified 的行。要添加更多级别,为新级别定义相同的结构,并修改 for 循环和 set_colour() 函数就足够了。

import logging
import re
import time
import sys

def set_colour(level):
    """
    Sets colour of text for the level name in
    logging statements using a dispatcher.
    """
    escaped = "[3[1;%sm%s3[1;0m]"
    return {
        'INFO': lambda: logging.addLevelName(logging.INFO, escaped % ('94', level)),
        'WARNING': lambda: logging.addLevelName(logging.ERROR, escaped % ('93', level)),
        'ERROR': lambda: logging.addLevelName(logging.WARNING, escaped % ('91', level)),
        'SUCCESS': lambda: logging.addLevelName(logging.SUCCESS, escaped % ('31', level))   # new
    }.get(level, lambda: None)()


class NoColorFormatter(logging.Formatter):
    """
    Log formatter that strips terminal colour
    escape codes from the log message.
    """

    # Regex for ANSI colour codes
    ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")

    def format(self, record):
        """Return logger message with terminal escapes removed."""
        return "%s %s %s" % (
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            re.sub(self.ANSI_RE, "", record.levelname),
            record.msg,
        )

def success(msg, *args, **kwargs):   # new
    if logging.getLogger().isEnabledFor(70):   # new
        logging.log(70, msg)   # new

# Create logger
logger = logging.getLogger(__package__)

# Create formatters
logformatter = NoColorFormatter()
colorformatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")

# Create new level
logging.SUCCESS = 70   # new
logging.success = success   # new
logging.Logger.success = success   # new

# Set logging colours
for level in 'INFO', 'ERROR', 'WARNING', 'SUCCESS':   # modified
    set_colour(level)

# Set logging level
logger.setLevel(logging.INFO)

# Set log handlers
loghandler = logging.FileHandler("log.txt", mode="w", encoding="utf8")
streamhandler = logging.StreamHandler(sys.stdout)

# Set log formatters
loghandler.setFormatter(logformatter)
streamhandler.setFormatter(colorformatter)

# Attach log handlers to logger
logger.addHandler(loghandler)
logger.addHandler(streamhandler)

# Example logging statements
logging.info("This is just an information for you")
logging.warning("This is just an information for you")
logging.error("This is just an information for you")
logging.success("This is just an information for you")