如何用python编写日志文件中的彩色文本

2024-04-26 21:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为日志文件.log 我使用写入文件的方式在该文件中写入不同的日志:

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

我如何用不同的颜色写日志(例如,红色代表错误,绿色代表信息,橙色代表调试)?在

我使用python2.5,因为它与我正在使用的另一个工具完全兼容。在


Tags: 文件infolog信息颜色错误方式代表
3条回答

您可以将color与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)

如果你想使用这个东西,那么创建你自己的日志

^{pr2}$

可以使用ANSI颜色代码将彩色线写入终端(请参见Printing to STDOUT and log file while removing ANSI color codes),但不能将彩色线写入文件。在

如果我错了请纠正我,但我认为您不能将彩色消息输出到utf-8日志文件。在

如前所述,您可以使用彩色CLI或尝试实现一个自己的记录器,该记录器将日志消息输出到html。Html可以实现着色。在

相关问题 更多 >