如何使用 loguru 接管程序的所有日志输出

我们自己写的代码,使用 loguru 来输出很方便,但是一些第三方的包对接的都是 Python 标准库中的 logging

比如启动 fastapi 服务的时候,会出现下面的日志:

─➤  python api.py
INFO:     Started server process [2382519]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

除此之外,还是 peewee 输出的 sql 等等

我都希望可以用 loguru 来输出日志,替换第三方库中的 logging

我该怎么做!

需要越简单优雅越好!

uvicorn 为例子, 我看到了,这篇文章:Configure uvicorn logs with loguru for FastAPI

文章中的方法,可以使得通过 uvicorn api:app 命令启动的程序起作用!

─➤  uvicorn api:app                                                                                                   1 ↵
2022-04-30 23:09:11.283 | INFO     | uvicorn.server:serve:75 - Started server process [2395776]
2022-04-30 23:09:11.283 | INFO     | uvicorn.lifespan.on:startup:45 - Waiting for application startup.
2022-04-30 23:09:11.283 | INFO     | uvicorn.lifespan.on:startup:59 - Application startup complete.
2022-04-30 23:09:11.284 | INFO     | uvicorn.server:_log_started_message:206 - Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

但是对于下面启动方式的程序不起作用:

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, workers=1)

可以看到 uvicorn 还是我行我素!

INFO:     Started server process [2394940]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
2022-04-30 23:07:39.367 | DEBUG    | middleware.loggers:__call__:15 - {"host": "127.0.0.1:8000", "user-agent": "HTTPie/1.0.3", "accept-encoding": "gzip, deflate", "accept": "*/*", "connection": "keep-alive"}
2022-04-30 23:07:39.371 | INFO     | __main__:root:28 - loguru info log
2022-04-30 23:07:39.371 | DEBUG    | __main__:root:32 - params with formating
{}
2022-04-30 23:07:39.371 | DEBUG    | __main__:root:37 - {'ip': '127.0.0.1'}
INFO:     127.0.0.1:54696 - "GET / HTTP/1.1" 200 OK
阅读 4.4k
2 个回答

看看loguru有没有重写logging的方法调用 建议用回logging一样方便

推荐问题
宣传栏