python日志记录-可以使用JSON日志向每个日志添加“额外”值吗?

时间:2019-02-01 01:29:49

标签: 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"})

但它好像我有工作。 :)

1 个答案:

答案 0 :(得分:1)

我只是用所需的自定义逻辑包装主日志记录类,

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')

希望这会有所帮助!