最近有一个需求:将日志以json格式输出, 并且有些字段是logging模块没有的.看了很多源码和资料, 终于搞定, 抽取精华分享出来, 一起成长.
import json
import logging
class JsonFilter(logging.Filter):
ip = 'IP'
source = 'APP'
def filter(self, record):
record.ip = self.ip
record.username = self.source
return True
if __name__ == '__main__':
formate = json.dumps({
"time": "%(asctime)s",
"levelname": "%(levelname)s",
"levelno": "%(lineno)d",
"ip": "%(ip)s",
"source": "%(source)s"
})
logging.basicConfig(level=logging.DEBUG,
format=formate)
logger = logging.getLogger()
filter_ = JsonFilter()
logger.addFilter(filter_)
logger.debug('A debug message')
filter_.ip = '127.0.0.1'
filter_.source= 'china'
logger.info('A message for test')
运行结果:
其实就是重写了logging.Filter的filter方法,自定义需要的字段, 在调用日志输出时,赋予相应的值即可.不赋予相应的值时也可以输出日志, 会自动按照定义字段时的信息输出.