在我的代码中,我在每个 LogRecord
上编写 dict-objects。其中一个键称为 my_msg
,我想创建一个 StreamHandler
,它只打印时间和 my_msg
键的值。
我已尝试以下操作,但收到错误消息:AttributeError: type object 'LogRecord' has no attribute 'levelname'
streamformatter = logging.Formatter(fmt='{}:\t{}'.format(logging.LogRecord.levelname, logging.LogRecord.message.get('my_msg'), datefmt='%H:%M:%S', style='{')
最佳答案
您需要将只是模板 传递给Formatter()
类。 稍后将使用该模板来格式化您的消息。您还需要使用命名插槽:
streamformatter = logging.Formatter(fmt='{levelname}:\t{my_msg}', datefmt='%H:%M:%S', style='{')
在创建 Formatter()
对象时,您不会对其调用 .format()
;那时还没有日志消息,也没有要填写的级别。
参见 logrecord attributes section默认情况下可用的名称;表格第二列中的任何 %
样式格式都应转换为新样式格式:
%(asctime)s
变为{asctime}
或{asctime!s}
%(created)f
变为{created:f}
%(lineno)d
变为{lineno:d}
。
等等
关于python - 如何在日志处理程序中指定 str.format() 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21160191/