gpt4 book ai didi

python - 自定义变量字段到python日志记录

转载 作者:行者123 更新时间:2023-11-28 21:42:46 25 4
gpt4 key购买 nike

我正在尝试在我的库中添加自定义格式字段。我知道这是通过 Filter 或 LoggerAdapter 对象完成的。但是,在我看到的示例中(例如:How do I add custom field to Python log format string?),他们想要生成的自定义字段是静态的,并且在创建记录器时已知。

我需要能够将变量发送到我的日志记录,直到我写日志记录之前我才真正知道。我想我只是没有看到解决方案,但如何才能最好地实现这一目标?

目前我是这样设置记录器的:

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)

在我的测试中我写:

my_obj = MyClass()
my_obj.logger.error('This is my error.', extra={'parameter': 'True'}

但这使得参数字段始终为“”(空字符串)。有没有办法为我每次进行日志调用(error()debug() 等)设置d 字典? )?

最佳答案

我对此进行了更深入的调查,LoggerAdapter 的“额外”参数在实际日志操作中优先于“额外”参数。 documentation 中也对此进行了描述.

要实现您想要的效果,您可以重写 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

这会将 LoggerAdapter 的额外参数与日志调用的参数合并。日志记录调用的参数优先。

关于python - 自定义变量字段到python日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com