如何在Python日志格式字符串中添加自定义字段? [英] How do I add custom field to Python log format string?
问题描述
我当前的格式字符串是:
My current format string is:
formatter = logging.Formatter('%(asctime)s : %(message)s')
我想添加一个名为app_name的新字段,在包含该格式化程序的每个脚本中,该字段将具有不同的值.
and I want to add a new field called app_name and which will have a different value in each script that contains this formatter.
import logging
formatter = logging.Formatter('%(asctime)s %(app_name)s : %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)
但是我不确定如何将app_name
值传递给记录器以内插到格式字符串中.我显然可以使它显示在日志消息中,但是每次都通过它,但这很麻烦.
But I'm not sure how to pass that app_name
value to the logger to interpolate into the format string. I can obviously get it to appear in the log message but passing it each time but this is messy.
我尝试过:
logging.info('Log message', app_name='myapp')
logging.info('Log message', {'app_name', 'myapp'})
logging.info('Log message', 'myapp')
,但无济于事.
推荐答案
您可以使用 LoggerAdapter ,因此您不必在每次记录调用时都传递额外的信息:
You could use a LoggerAdapter so you don't have to pass the extra info with every logging call:
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
过滤器也可以用于添加上下文信息.
Filters can also be used to add contextual information.
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')
产生类似的日志记录.
这篇关于如何在Python日志格式字符串中添加自定义字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!