无法获取此自定义日志适配器examp

2024-05-22 00:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里查看了与上下文日志相关的示例: 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。在


Tags: thetologadaptersoismylogging
1条回答
网友
1楼 · 发布于 2024-05-22 00:51:41

您必须使用适配器进行日志记录,而不是使用记录器。试试这个:

import logging

class CustomAdapter(logging.LoggerAdapter):
    def process(self, msg, kwargs):
        # use my_context from kwargs or the default given on instantiation
        my_context = kwargs.pop('my_context', self.extra['my_context'])
        return '[%s] %s' % (my_context, msg), kwargs

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')
adapter.info('The sky is so blue')

输出:

^{pr2}$

相关问题 更多 >