seo 优化

  • loguru 去掉部分字段
  • loguru 去掉 record 字段
  • loguru 如何只留下自己想要的字段
  • 自定义 loguru 输出

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": {}}}

原理:我们用自己的 _serialize_record 函数替换了 loguru/_handler.py 中的 _serialize_record 函数。

loguru/_handler.py 中的 _serialize_record 函数长这样:

@staticmethod
def _serialize_record(text, record):
    exception = 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": {
            "elapsed": {
                "repr": record["elapsed"],
                "seconds": record["elapsed"].total_seconds(),
            },
            "exception": exception,
            "extra": record["extra"],
            "file": {"name": record["file"].name, "path": record["file"].path},
            "function": record["function"],
            "level": {
                "icon": record["level"].icon,
                "name": record["level"].name,
                "no": record["level"].no,
            },
            "line": record["line"],
            "message": record["message"],
            "module": record["module"],
            "name": record["name"],
            "process": {"id": record["process"].id, "name": record["process"].name},
            "thread": {"id": record["thread"].id, "name": record["thread"].name},
            "time": {"repr": record["time"], "timestamp": record["time"].timestamp()},
        },
    }

    return json.dumps(serializable, default=str, ensure_ascii=False) + "\n"

可以根据实际需求,来取省字段


universe_king
3.4k 声望680 粉丝