如何在Python日志文件中写入彩色文本

-1 投票
3 回答
3884 浏览
提问于 2025-04-17 20:54

我有一个日志文件,名字叫 LogFile.log。我在这个文件里写入不同的日志,使用的是写入文件的方式:

logfile = open(LogFile.log, 'a')
logFile.write("<< INFO >> ")

我该怎么用不同的颜色来写我的日志呢(比如,错误用红色,信息用绿色,调试用橙色)?

我正在使用 Python 2.5,因为它和我正在使用的另一个工具完全兼容。

3 个回答

-4

你可以把颜色和Python的日志模块结合起来使用。

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%(name)-20s$RESET][%(levelname)-18s]  %(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


logging.setLoggerClass(ColoredLogger)
-1

如果我说错了请纠正我,但我觉得你不能把带颜色的消息输出到一个utf-8编码的日志文件里。

之前提到过,你可以使用带颜色的命令行界面,或者尝试自己实现一个记录器,比如把日志信息输出到html文件里。因为html可以实现颜色显示。

1

你可以使用ANSI颜色代码在终端上写出彩色的文字(详细内容可以查看如何在输出和日志文件中打印并去除ANSI颜色代码),但是你不能把彩色的文字写入文件。

撰写回答