3

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

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

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

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

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

4

2 回答 2

2

我会用我需要的自定义逻辑来包装主日志记录类,如下所示:

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

希望这可以帮助!

于 2019-02-01T02:32:16.110 回答
1

如果您正在使用python-json-logger并拥有自定义格式化程序类,则可以直接在方法中添加这些log_record字段add_fields()

from pythonjsonlogger import jsonlogger
from datetime import datetime
import logging
import json


logger = logging.getLogger()

logHandler = logging.StreamHandler()
class CustomJsonFormatter(jsonlogger.JsonFormatter):
    def add_fields(self, log_record, record, message_dict):
        super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
        if not log_record.get('datetime'):
            log_record['datetime'] = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')
        if log_record.get('level'):
            log_record['level'] = log_record['level'].upper()
        else:
            log_record['level'] = record.levelname
        log_record['app_name']='myapp'
        log_record['env']='prod'

formatter = CustomJsonFormatter('%(datetime)s %(level)s %(message)s')

logHandler.setFormatter(formatter)
logger.addHandler(logHandler)
logger.setLevel(logging.INFO)
logger.info("Something happened.")

这打印出来:

{
 "datetime": "2021-12-28T23:43:25.503081Z", 
 "level": "INFO", 
 "message": "Something happened.", 
 "app_name": "myapp", 
 "env": "prod"
}
于 2021-12-28T23:46:50.630 回答