我正在使用Python的logging模块,以及python-json-logger,我想添加一些键:
{
"app_name": "myapp",
"env": "prod"
}
自动记录所有日志,无需执行以下操作。
logger.info("Something happened", extra={"app_name": "myapp", "env": "prod"})
但需要它能够像我一样工作。 :)
我正在使用Python的logging模块,以及python-json-logger,我想添加一些键:
{
"app_name": "myapp",
"env": "prod"
}
logger.info("Something happened", extra={"app_name": "myapp", "env": "prod"})
如果您正在使用python-json-logger
并且有自定义格式化程序类,则可以在add_fields()
方法中直接添加这些字段到log_record
中。
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"
}
我只是这样包装了主要的日志类与我所需要的自定义逻辑:
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')