将自定义值传递给记录器,而不是传递给每条消息 [英] Pass custom value to the logger instead of to every message

查看:51
本文介绍了将自定义值传递给记录器,而不是传递给每条消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要记录用户会话.当前代码如下(设置格式化程序和处理程序已省略):

I want to log the user session. Currently the code is as follows (setting formatter and handlers is omitted):

logger = logging.getLogger("component")
logger.info("message", extra={"session": 123})
logger.debug("debug", extra={"session": 123})

如果要记录几条消息,则每次发送此额外信息都很烦人.实现这样的最佳/最干净/最pythonic方法是什么:

If there are several messages to be logged, it's annoying to send this extra information each time. What would be the best/cleanest/most pythonic way to achieve something like that:

logger = logging.getLogger("component")
# for example:
logger.addExtra({"session": 123})
logger.info("message") # extra would be added automatically
logger.debug("debug") # extra would be added automatically

我可以考虑扩展记录器并覆盖日志记录方法.

I could think of extending the logger and overriding logging methods.

推荐答案

按照指定的@DhruvPathak创建LoggerAdapter.根据 LoggerAdapter签名:

Create a LoggerAdapter as @DhruvPathak specified. According to LoggerAdapters signature:

class logging.LoggerAdapter(logger, extra)

您可以通过在初始化期间提供记录器实例和extra args来做到这一点:

you do that by providing your logger instance and the extra args during initialization:

logger = logging.LoggerAdapter(logger, extra)

这篇关于将自定义值传递给记录器,而不是传递给每条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆