我使用Python logging模块,沿着python-json-logger和我想补充几个键:
{
"app_name": "myapp",
"env": "prod"
}
要所有我的日志的情况下自动执行以下操作。
logger.info("Something happened", extra={"app_name": "myapp", "env": "prod"})
但它好像我有工作。 :)
答案 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')
希望这会有所帮助!