乐趣区

关于python:loguru-添加默认的-extra

翻看了一下 loguru 的源代码

loguru 有很恶心的 pyi 文件来影响咱们看源代码,倡议删除 pyi 后再看。python 删除 pyi 文件

能够应用 logger.bind, 然而 logger.bind 会返回一个新的 logger,当前都要应用这个新的 logger 才行

ll=logger.bind(project_name="ideaboom")

参考文章:How to use Loguru defaults + and extra information?

loguru 貌似没有提供原地批改的形式,只能通过这种 logger.bind 生成一个新的 logger 的形式

残缺代码:

from loguru._recattrs import RecordException
from loguru._handler import Handler
from loguru import logger
import sys
import json


logger.remove()

logger.add(sys.stdout, serialize='json')

ll=logger.bind(project_name="ideaboom")

ll.debug('哈哈哈')

从上面的运行后果,能够看到,extra 中曾经带上 project_name 了

╰─➤  python -u "/Users/ponponon/Desktop/code/me/ideaboom/test_logger/003.py"
{"text": "2022-10-19 09:25:42.082 | DEBUG    | __main__:<module>:14 - 哈哈哈 \n", "record": {"elapsed": {"repr": "0:00:00.005543", "seconds": 0.005543}, "exception": null, "extra": {"project_name": "ideaboom"}, "file": {"name": "003.py", "path": "/Users/ponponon/Desktop/code/me/ideaboom/test_logger/003.py"}, "function": "<module>", "level": {"icon": "🐞", "name": "DEBUG", "no": 10}, "line": 14, "message": "哈哈哈", "module": "003", "name": "__main__", "process": {"id": 41288, "name": "MainProcess"}, "thread": {"id": 4300178816, "name": "MainThread"}, "time": {"repr": "2022-10-19 09:25:42.082610+08:00", "timestamp": 1666142742.08261}}}

为了不便各位看官看,我把这条日志格式化一下

{
  "text": "2022-10-19 09:25:42.082 | DEBUG    | __main__:<module>:14 - 哈哈哈 \n",
  "record": {"elapsed": { "repr": "0:00:00.005543", "seconds": 0.005543},
    "exception": null,
    "extra": {"project_name": "ideaboom"},
    "file": {
      "name": "003.py",
      "path": "/Users/ponponon/Desktop/code/me/ideaboom/test_logger/003.py"
    },
    "function": "<module>",
    "level": {"icon": "🐞", "name": "DEBUG", "no": 10},
    "line": 14,
    "message": "哈哈哈",
    "module": "003",
    "name": "__main__",
    "process": {"id": 41288, "name": "MainProcess"},
    "thread": {"id": 4300178816, "name": "MainThread"},
    "time": {
      "repr": "2022-10-19 09:25:42.082610+08:00",
      "timestamp": 1666142742.08261
    }
  }
}

如果你感觉这个 json 蕴含了太多非必要字段了,能够参考解决: loguru serialize 缩小字段

退出移动版