本文介绍了如何在记录器格式化程序中输入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前有:
FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S', filename=LOGFILE, level=getattr(logging, options.loglevel.upper()))
...效果很好,但是我正在尝试做:
... which works great, however I'm trying to do:
FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
,即使定义了MYVAR
,也只会引发键盘错误.
and that just throws keyerrors, even though MYVAR
is defined.
有解决方法吗? MYVAR
是一个常量,因此每次调用记录器时都必须传递它是一个可耻的事情.
Is there a workaround? MYVAR
is a constant, so it would be a shame of having to pass it everytime I invoke the logger.
谢谢!
推荐答案
您可以使用:
import logging
MYVAR = 'Jabberwocky'
class ContextFilter(logging.Filter):
"""
This is a filter which injects contextual information into the log.
"""
def filter(self, record):
record.MYVAR = MYVAR
return True
FORMAT = '%(MYVAR)s %(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT, datefmt='%d/%m/%Y %H:%M:%S')
logger = logging.getLogger(__name__)
logger.addFilter(ContextFilter())
logger.warning("'Twas brillig, and the slithy toves")
收益
Jabberwocky 24/04/2013 20:57:31 - WARNING - 'Twas brillig, and the slithy toves
这篇关于如何在记录器格式化程序中输入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!