在Python web服务中,有时候为了便于日志采集工具(filebeat等)采集日志信息,需要输出JSON格式的日志。可以采用Python中pythonjsonlogger
包将日志格式转换为JSON输出。
安装
pip install python-json-logger
使用
import logging
from pythonjsonlogger import jsonlogger
logger = logging.getLogger()
ch = logging.StreamHandler()
ch.setFormatter(jsonlogger.JsonFormatter())
logger.setLevel(logging.INFO)
logger.addHandler(ch)
logger.info({"special": "value", "run": 12})
logger.info("classic message", extra={"special": "value", "run": 12})
logger.info("asda%s", 123)
'''
{"message": null, "special": "value", "run": 12}
{"message": "classic message", "special": "value", "run": 12}
{"message": "asda123"}
'''
在项目中可以自行设置需要输出的JSON
格式日志信息。