boy*_*ode 2 python logging class
我试图在我的图书馆中添加自定义格式字段。我知道这是通过Filter或LoggerAdapter对象完成的。但是,在我看到的示例中(像这样的示例:如何向Python日志格式字符串中添加自定义字段?),他们想要生成的自定义字段是静态的,并且在创建记录器时就知道了。
我需要能够将直到我写日志记录之前才真正知道的变量发送到我的日志记录。我想我只是没有看到解决方案,但是如何最好地做到这一点?
目前,我以这种方式设置记录器:
import logging
class MyClass:
filehandler = logging.handlers.RotatingRileHandler(r'C:\Users\Me\Desktop\Logs',
maxBytes=1000000, backupCount=4, encoding='ASCII')
formatter = logging.Formatter('[%(asctime)s] : %(levelname)-8s: Para: %(parameter)-15s'
' - %(message)s')
# parameter is my custom name I want to inject
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self.logger.addHandler(file_handler)
d = {'parameter': ''}
self.logger = logging.LoggerAdapter(self.logger, extra=d)
Run Code Online (Sandbox Code Playgroud)
在测试中,我写道:
my_obj = MyClass()
my_obj.logger.error('This is my error.', extra={'parameter': 'True'}
Run Code Online (Sandbox Code Playgroud)
但这会使参数字段''(空白字符串)始终为。有没有一种方法来设置d
字典中的每个我使日志调用(时间error()
,debug()
等等)?
我对此进行了进一步的研究,在实际的日志操作中,LoggerAdapter的“额外”参数优先于“额外”参数。文档中也对此进行了描述。
要实现所需的功能,可以重写LoggerAdapter类并按如下所示自定义处理方法:
class CustomLoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
"""
Process the Logging message and keyword arguments passed in to
a logging call to insert contextual information. The extra argument
of the LoggerAdapter will be merged with the extra argument of the
logging call where the logging call's argument take precedence.
"""
try:
kwargs["extra"] = {**self.extra, **kwargs["extra"]}
except KeyError as e:
kwargs["extra"] = self.extra
return msg, kwargs
Run Code Online (Sandbox Code Playgroud)
这会将LoggerAdapter的额外参数与日志记录调用的参数合并。记录调用的参数优先。