关于python:loguru-serialize-减少字段

42次阅读

共计 1427 个字符,预计需要花费 4 分钟才能阅读完成。

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__:<module>: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": "<module>", "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__:<module>:35 - 哈哈 \n", "record": {"extra": {}}}

正文完
 0