我在这里查看了与上下文日志相关的示例: Logging Cookbook
但是,我不能让下面的例子起作用。示例应演示自定义适配器的使用,并按以下方式继续:
# Here is a simple example:
class CustomAdapter(logging.LoggerAdapter):
"""
This example adapter expects the passed in dict-like object to have a
'connid' key, whose value in brackets is prepended to the log message.
"""
def process(self, msg, kwargs):
return '[%s] %s' % (self.extra['connid'], msg), kwargs
# which you can use like this:
logger = logging.getLogger(__name__)
adapter = CustomAdapter(logger, {'connid': some_conn_id})
# Then any events that you log to the adapter will have the value of some_conn_id prepended to the log messages.
然而,不管我做了什么,我总是会得到一个关键错误:
^{pr2}$我做错什么了?在
---解决方案:编辑_01---
我已经更改了代码,使其使用adapter.info('The sky is so blue', {'my_context': '6642'})
。而且成功了。但是,我不得不从格式化程序中删除my_context
。但是,使用下面的代码,my_context
位是硬编码的,无论我通过记录器传入什么,它都将始终显示初始值。有没有办法把一些值传递给适配器?在
logger = logging.getLogger(__name__)
syslog = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(message)s')
syslog.setFormatter(formatter)
logger.addHandler(syslog)
adapter = CustomAdapter(logger, {'my_context': '1956'})
logger.setLevel(logging.INFO)
adapter.info('The sky is so blue', {'my_context': '6642'})
这将始终产生:
2016-09-13 11:33:18,404 [1956] The sky is so blue
甚至我们正在通过记录器传递6642
。在
您必须使用适配器进行日志记录,而不是使用记录器。试试这个:
输出:
^{pr2}$相关问题 更多 >
编程相关推荐