用于日志记录的json格式化程序
logformatjson的Python项目详细描述
logformatjson是一个库,它为标准python日志记录包提供了一个简单的json格式化程序。它允许在实例化和运行时插入嵌套的任意元数据。图书馆有意见,但试图让大多数意见被推翻。
警告:此库正在积极开发中。日志格式和api预计将更改。
安装
- 通过pip:
pip install logformatjson
示例
- 基本用法-jsonformatter可以按预期设置在任何处理程序上:
importloggingimportsysfromlogformatjsonimportJSONFormatterLOGGER=logging.getLogger()LOGGER.setLevel(logging.DEBUG)log_handler=logging.StreamHandler(sys.stdout)log_handler.setFormatter(JSONFormatter())LOGGER.addHandler(log_handler)LOGGER.debug('this is my debug message',extra={'some_key':'important_value'})
它生成以下json(来自ipython):
{"timestamp":"2016-02-19T19:39:17.061886","message":"this is my debug message","levelname":"DEBUG","metadata":{"filename":"test.py","funcName":"<module>","extra":{"some_key":"important_value"},"log_type":"python","lineno":11,"module":"test","pathname":"test.py"},"log_version":"1.0"}
- 在every中添加附加元数据日志条目:
…log_handler.setFormatter(JSONFormatter(metadata={'application_version':'1.0.0'}))…
在实例化时重写默认值:
- Override attributes copied or skipped from the LogRecord:
…log_handler.setFormatter(JSONFormatter(kept_attrs=['created',…]))log_handler.setFormatter(JSONFormatter(skipped_attrs=['filename',…]))…
Override the provided json encoder:
defmy_json_encoder(obj):returnint(obj)…log_handler.setFormatter(JSONFormatter(json_encoder=my_json_encoder))…
在运行时覆盖默认值:
Log type (intended to be mixed with extra fields):
…logger.debug('GET / HTTP/1.1',log_type='HTTP'}…
额外字段:
…LOGGER.debug('this is my debug message',extra={'some_key':'important_value'})…
测试
测试可以通过make:
运行make lint
make test