如何将自定义字段添加到Python日志格式string?
我目前的格式string是:
formatter = logging.Formatter('%(asctime)s : %(message)s')
我想添加一个名为app_name的新字段,并在每个包含此格式化程序的脚本中使用不同的值。
import logging formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s') syslog.setFormatter(formatter) logger.addHandler(syslog)
但我不知道如何将该app_name
值传递给logging器插入格式string。 我显然可以让它出现在日志消息,但每次都传递,但这是混乱。
我试过了:
logging.info('Log message', app_name='myapp') logging.info('Log message', {'app_name', 'myapp'}) logging.info('Log message', 'myapp')
但没有工作。
您可以使用LoggingAdapter,因此您不必在每次调用日志时都传递额外的信息:
import logging extra = {'app_name':'Super App'} logger = logging.getLogger(__name__) syslog = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s') syslog.setFormatter(formatter) logger.setLevel(logging.INFO) logger.addHandler(syslog) logger = logging.LoggerAdapter(logger, extra) logger.info('The sky is so blue')
日志(类似的东西)
2013-07-09 17:39:33,596 Super App : The sky is so blue
filter也可以用来添加上下文信息。
import logging class AppFilter(logging.Filter): def filter(self, record): record.app_name = 'Super App' return True logger = logging.getLogger(__name__) logger.addFilter(AppFilter()) syslog = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s') syslog.setFormatter(formatter) logger.setLevel(logging.INFO) logger.addHandler(syslog) logger.info('The sky is so blue')
产生一个类似的日志logging。
您需要将dict作为parameter passing给额外的用户。
logging.info('Log message', extra={'app_name': 'myapp'})
certificate:
>>> import logging >>> logging.basicConfig(format="%(foo)s - %(message)s") >>> logging.warning('test', extra={'foo': 'bar'}) bar - test
此外,请注意,如果您尝试logging不通过字典的消息,则会失败。
>>> logging.warning('test') Traceback (most recent call last): File "/usr/lib/python2.7/logging/__init__.py", line 846, in emit msg = self.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 723, in format return fmt.format(record) File "/usr/lib/python2.7/logging/__init__.py", line 467, in format s = self._fmt % record.__dict__ KeyError: 'foo' Logged from file <stdin>, line 1