翻看了一下 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 减少字段

universe_king
3.4k 声望680 粉丝