Python Colorlog 未在带有颜色的日志文件中打印 [英] Python Colorlog not printing in the log files with colors

查看:99
本文介绍了Python Colorlog 未在带有颜色的日志文件中打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Python colorlogs 为不同级别的日志设置不同的颜色.当我运行代码时,控制台日志是彩色的,但日志文件没有颜色.我正在使用以下代码

I'm using Python colorlogs for having different colors for different levels of logs. When i'm running the code the console logs are in colors but the log file does not have colors. I'm using the below code

def setup_logger(logfiletouse):
    """Return a logger with a default ColoredFormatter."""
    formatter = colorlog.ColoredFormatter(
        "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
        datefmt=None,
        reset=True,
        log_colors={
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red',
        }
    )

    log = logging.getLogger(logfiletouse)

    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    return log

这是我第一次尝试使用 Python 颜色日志.任何帮助表示赞赏.

This is my first attempt of using Python colorlogs. Any help is appreciated.

推荐答案

colorlog 和大多数其他终端着色库使用的彩色输出通过 shell 的转义序列更改用户终端的属性.

The colored output used by colorlog and most other terminal coloring libraries changes properties of the user terminal, through the shell's escape sequences.

在实践中,这将打印人类不可读的 shell 转义序列,例如 \[\033[34m\].您的 shell 负责将这些序列解析为显示器上的颜色.

In practice, this will print shell escape sequences which are not human readable, such as \[\033[34m\]. Your shell is responsible for parsing these sequences into colors on your display.

纯文本文件不支持编码到其中的颜色信息,因此通常在写入文件时,所有日志记录工具都会关闭颜色支持,否则您的日志文件中会出现乱码.想想一个到处都是那些不可读的转义序列的纯文本文件.

A plain text file does not support color information encoded into it, so generally when writing to files, all logging tools will turn off the color support, or else you would get mangled text in your log files. Just think of a plain text file packed with those unreadable escape sequences everywhere.

有关外壳着色和转义序列的更多信息,您可以查看 http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html(特定于 bash,在其他 shell 上类似)

For more information on shell coloring and escape sequences you can take a look at http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html (bash specific, similar on other shells)

这篇关于Python Colorlog 未在带有颜色的日志文件中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆