如何在Python logging.Formatter 格式化

我目前正在尝试居中与👉Python记录器中的日志记录级别字段,输出如下:

[    test_log    ][    DEBUG]  test (color_logger.py:66)
[    test_log    ][     INFO]  test (color_logger.py:67)
[    test_log    ][  WARNING]  test (color_logger.py:68)
[    test_log    ][    ERROR]  test (color_logger.py:69)
[    test_log    ][ CRITICAL]  test (color_logger.py:70)

但看起来像:

[__main__][DEBUG]  test (color_logger.py:67)
[__main__][INFO]  test (color_logger.py:68)
[__main__][WARNING]  test (color_logger.py:69)
[__main__][ERROR]  test (color_logger.py:70)
[__main__][CRITICAL]  test (color_logger.py:71)

有两个问题,

  • funcName 而不是 name

  • 得考虑右对齐和居中

解决方法

import logging

BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)

#The background is set with 40 plus the number of the color, and the foreground with 30
#These are the sequences need to get colored ouput
RESET_SEQ = "\033[0m"
COLOR_SEQ = "\033[1;%dm"
BOLD_SEQ = "\033[1m"

def formatter_message(message, use_color = True):
    if use_color:
        message = message.replace("$RESET", RESET_SEQ).replace("$BOLD", BOLD_SEQ)
    else:
        message = message.replace("$RESET", "").replace("$BOLD", "")
    return message

COLORS = {
    'WARNING': YELLOW,
    'INFO': WHITE,
    'DEBUG': BLUE,
    'CRITICAL': YELLOW,
    'ERROR': RED
}

class ColoredFormatter(logging.Formatter):
    def __init__(self, msg, use_color = True):
        logging.Formatter.__init__(self, msg)
        self.use_color = use_color

    def format(self, record):
        levelname = record.levelname
        if self.use_color and levelname in COLORS:
            levelname_color = COLOR_SEQ % (30 + COLORS[levelname]) + levelname + RESET_SEQ
            record.levelname = levelname_color
        return logging.Formatter.format(self, record)



# Custom logger class with multiple destinations
class ColoredLogger(logging.Logger):
    FORMAT = "[$BOLD" + "%(funcName)s".center(20," ")+"$RESET]["+ "%(levelname)20s" +"]  %(message)s ($BOLD%(filename)s$RESET:%(lineno)d)"
    COLOR_FORMAT = formatter_message(FORMAT, True)
    def __init__(self, name):
        logging.Logger.__init__(self, name, logging.DEBUG)                

        color_formatter = ColoredFormatter(self.COLOR_FORMAT)

        console = logging.StreamHandler()
        console.setFormatter(color_formatter)

        self.addHandler(console)
        return