在我的代码中,我从我的客户端获得了一个记录器,然后我做一些事情并将我的分析记录到记录器中。
我想将我自己的前缀添加到记录器,但我不想创建自己的格式化程序,只是为了将我的前缀添加到现有的格式程序中。
此外,一旦我的代码完成,我想删除我的前缀。
通过查看文档,我只能找到创建新格式化程序而不是修改现有格式化程序的方法。有没有办法这样做?
最佳答案
你是对的。根据 Python 3 和 Python 2 文档,无法在现有格式化程序对象上重置格式,您需要创建新的 logging.Formatter
对象。然而,在运行时查看对象有 _fmt
方法来获取现有格式,似乎调整它会起作用。我在 2.7 中尝试过,它有效。下面是示例。
python 2.7的示例代码:
import logging
logger = logging.getLogger('something')
myFormatter = logging.Formatter('%(asctime)s - %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(myFormatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
logger.info("log statement here")
#Tweak the formatter
myFormatter._fmt = "My PREFIX -- " + myFormatter._fmt
logger.info("another log statement here")
输出:
2015-03-11 12:51:36,605 - log statement here
My PREFIX -- 2015-03-11 12:51:36,605 - another log statement here
关于python - 如何为现有的 python 日志格式化程序添加前缀,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28994448/