loguru serialize 默认的字段太多了,大多数根本不需要,大大浪费了日志存储空间:
from loguru import logger
import sys
logger.remove()
logger.add(sys.stdout, serialize='json')
logger.debug(f'哈哈')
输出:
{"text": "2022-08-28 01:11:45.258 | DEBUG | __main__::9 - 哈哈\n", "record": {"elapsed": {"repr": "0:00:00.004474", "seconds": 0.004474}, "exception": null, "extra": {}, "file": {"name": "003.py", "path": "/home/bot/Desktop/ideaboom/test_logger/003.py"}, "function": "", "level": {"icon": "", "name": "DEBUG", "no": 10}, "line": 9, "message": "哈哈", "module": "003", "name": "__main__", "process": {"id": 282787, "name": "MainProcess"}, "thread": {"id": 139949730423424, "name": "MainThread"}, "time": {"repr": "2022-08-28 01:11:45.258317+08:00", "timestamp": 1661620305.258317}}}
我们需要减少这些没用的字段
使用类似『猴子补丁』的方式来实现:
from loguru._recattrs import RecordException
from loguru._handler import Handler
from loguru import logger
import sys
import json
def _serialize_record(text: str, record: dict):
exception: RecordException = record["exception"]
if exception is not None:
exception = {
"type": None if exception.type is None else exception.type.__name__,
"value": exception.value,
"traceback": bool(exception.traceback),
}
serializable = {
"text": text,
"record": {
"extra": record["extra"],
},
}
return json.dumps(serializable, default=str, ensure_ascii=False) + "\n"
Handler._serialize_record = staticmethod(_serialize_record)
logger.remove()
logger.add(sys.stdout, serialize='json')
logger.debug(f'哈哈')
输出:
{"text": "2022-08-28 01:10:55.326 | DEBUG | __main__::35 - 哈哈\n", "record": {"extra": {}}}