可以根据消息日志级别修改 Python 的日志记录格式吗? [英] Can Python's logging format be modified depending on the message log level?

查看:29
本文介绍了可以根据消息日志级别修改 Python 的日志记录格式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 的 logging 机制将输出打印到屏幕上.我可以用打印语句来做到这一点,但我希望允许用户更精细地调整粒度以禁用某些类型的输出.我喜欢为错误打印的格式,但当输出级别为信息"时更喜欢更简单的格式.

例如:

 logger.error("运行cmd失败")logger.info("运行cmd通过")

在这个例子中,我希望以不同的方式打印错误的格式:

<块引用>

# 错误2009 年 8 月 27 日 - 错误:运行 cmd 失败# 信息运行cmd通过

在没有多个日志对象的情况下,是否可以为不同的日志级别使用不同的格式?我更愿意在创建记录器后不修改它的情况下执行此操作,因为有大量 if/else 语句来确定应如何记录输出.

解决方案

是的,您可以通过自定义 Formatter 类来实现:

class MyFormatter(logging.Formatter):定义格式(自我,记录):#根据record.levelno计算s#例如,通过设置self._fmt#根据levelno,然后调用#进行实际格式化的超类返回

然后将 MyFormatter 实例附加到您的处理程序.

I'm using Python's logging mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."

For example:

  logger.error("Running cmd failed")
  logger.info("Running cmd passed")

In this example, I would like the format of the error to be printed differently:

# error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed

Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.

解决方案

Yes, you can do this by having a custom Formatter class:

class MyFormatter(logging.Formatter):
    def format(self, record):
        #compute s according to record.levelno
        #for example, by setting self._fmt
        #according to the levelno, then calling
        #the superclass to do the actual formatting
        return s

Then attach a MyFormatter instance to your handlers.

这篇关于可以根据消息日志级别修改 Python 的日志记录格式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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