使用jsonlogger库将日志输出为json格式,方便后续对日志进行处理,代码如下:
# -*- coding: utf-8 -*-import loggingfrom pythonjsonlogger import jsonloggerlogger = logging.getLogger()ch = logging.StreamHandler() // 输出到标准输出fmt = jsonlogger.JsonFormatter('%(asctime)s %(name)s %(levelname)s %(filename)s %(funcName)s:%(lineno)d %(message)s')ch.setFormatter(fmt)logger.setLevel(logging.DEBUG)logger.addHandler(ch)logger.info("PROGRESS", extra={"event_type": "EventType.PROGRESS", "status": "运行中", "total": 100, "current": 5})
但是发现,当日志有中文会有编码问题,如图
查看源码,在JsonFormatter类中,发现可以通过设置json_ensure_ascii来设置json.dumps时的ensure_ascii参数,json.dumps()设置ensure_ascii=False,防止ascii编码,保证中文输出。
修改如下:
fmt = jsonlogger.JsonFormatter('%(asctime)s %(name)s %(levelname)s %(filename)s %(funcName)s:%(lineno)d %(message)s', json_ensure_ascii=False)
再次运行,中文可以正常输出: