python 日志记录 - 使用 JSON 日志,我可以向每个日志添加 "extra"值吗?

标签 python python-3.x python-logging structured-logging

我正在使用 python logging模块,以及 python-json-logger我想添加一些键:

{
  "app_name": "myapp",
  "env": "prod"
}

无需执行以下操作即可自动转到我的所有日​​志。

logger.info("Something happened", extra={"app_name": "myapp", "env": "prod"})

但要让它像我一样工作。 :)

最佳答案

我会像这样用我需要的自定义逻辑包装主日志记录类:

import logging

class CustomLogger(object):
    def __init__(self, logger_name, log_format, extra=None):
        logging.basicConfig(format=log_format)
        self.logger = logging.getLogger(logger_name)
        self.extra = extra

    def debug(self, msg, *args, **kwargs):
        self.logger.debug(msg, *args, extra=self.extra, **kwargs)

    def info(self, msg, *args, **kwargs):
        self.logger.info(msg, *args, extra=self.extra, **kwargs)

    def warning(self, msg, *args, **kwargs):
        self.logger.warning(msg, *args, extra=self.extra, **kwargs)

    def error(self, msg, *args, **kwargs):
        self.logger.error(msg, *args, extra=self.extra, **kwargs)

然后在任何需要记录器的地方从该类创建它:

from custom_logging import CustomLogger

logger_name = 'my_logger'       
log_format = '%(asctime)-15s %(app_name)-8s %(env)-8s %(message)s'
extras = {"app_name": "myapp", "env": "prod"}

logger = CustomLogger(logger_name, log_format, extras)
logger.info('Testing it out')

希望这对您有所帮助!

关于python 日志记录 - 使用 JSON 日志,我可以向每个日志添加 "extra"值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471689/

相关文章:

python - 如何在 zeep 中使用 wsdl 的每种方法发送 header ?

python - 登录 Python/Django 未按预期工作

python - 使用 Python 查找函数的两个零点

python - 根据日期条件创建列,但出现此错误 AttributeError : 'SeriesGroupBy' object has no attribute 'sub' ?

Django .get() 返回一个元组而不是对象

将嵌套缩进文本解析为列表

python - Python 中的 My.Resources(vb.net) 相当于什么?

python - 如何从命令行获取 linux screen 标题

python - 我可以将环境变量添加到 python 记录器 ini 文件配置中吗?

python - 如何将自定义日志级别添加到 Python 的日志记录工具