时间:2022-06-23 11:39:00 | 栏目:Python代码 | 点击:次
最近有一个需求:将日志以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方法,自定义需要的字段, 在调用日志输出时,赋予相应的值即可.不赋予相应的值时也可以输出日志, 会自动按照定义字段时的信息输出.
补充知识:Log打印完整参数,生成Json文件
当字符数量足够多的的时候,Log控制台便会自动截取,不能在控制台上完整输出,可以利用如下方法,这种方式会在测试机或者虚拟机的根目录生成一个new.json文件,里面是完整的Log信息
public static void printStringToFile(String str) { File file = new File(Environment.getExternalStorageDirectory(), "new.json"); Log.d("Lyb", "path = " + file.getAbsolutePath()); FileWriter writer = null; try { Log.d("Lyb", "createNewFile"); if (!file.exists()) { file.createNewFile(); }else { file.delete(); file.createNewFile(); } writer = new FileWriter(file, true); writer.write(str); writer.flush(); writer.close(); writer = null; } catch (IOException e) { e.printStackTrace(); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { e.printStackTrace(); } } }