使用 loggging 模块做日志, console 输出内容,都是红色,应该怎么调?

2019-09-20 14:33:40 +08:00
 qazwsxkevin

我是这么干的:

    #生成日志
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log 等级总开关
    LogFileHandler = logging.FileHandler(MatchDir + 'log.log', mode='a')
    LogFileHandler.setLevel(logging.NOTSET)  # 输出到 file 的 log 等级的开关
    # # 定义在 console 输出的日志颜色
    # COLORS = {
    # 'DEBUG': 'cyan',
    # 'INFO': 'green',
    # 'WARNING': 'yellow',
    # 'ERROR': 'red',
    # 'CRITICAL': 'red',
    # }
    # 输出到 console 的日志
    ConsoleHanler = logging.StreamHandler()
    ConsoleHanler.setLevel(logging.INFO)
    # 定义 handler 的输出格式
    formatter = logging.Formatter("[%(asctime)s]_[line:%(lineno)d]-[%(levelname)s] %(message)s",datefmt='%Y-%m-%d %H:%M:%S')
    LogFileHandler.setFormatter(formatter)
    ConsoleHanler.setFormatter(formatter)
    # 将 logger 添加到 handler 里面
    logger.addHandler(LogFileHandler)
    logger.addHandler(ConsoleHanler)

情况是,在 pccharm console 输出的内容,无论是哪个级别的日志,都是默认红色的字体,
尽管查过一些资料和 logging 模块的说明,相信应该是 Formatter 上设置,很多介绍没有一个例子来解疑惑,或者能成功的例子不是我上面这种思路的。。。

3074 次点击
所在节点    Python
2 条回复
AntiGameZ
2019-09-20 14:42:24 +08:00
vkhsyj
2019-09-20 15:13:19 +08:00
StreamHandler 默认输出到 stderr,设置一下就好了
class logging.StreamHandler(stream=None)
Returns a new instance of the StreamHandler class. If stream is specified, the instance will use it for logging output; otherwise, sys.stderr will be used.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/602539

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX