简体   繁体   English

如何在 uvicorn 日志中为每个请求添加时间戳?

[英]How to add timestamp to each request in uvicorn logs?

When I run my FastAPI server using uvicorn:当我使用 uvicorn 运行我的 FastAPI 服务器时:

uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info

The log I get after running the server:运行服务器后我得到的日志:

INFO:     Started server process [405098]
INFO:     Waiting for application startup.
INFO:     Connect to database...
INFO:     Successfully connected to the database!
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     122.179.31.158:54604 - "GET /api/hello_world?num1=5&num2=10 HTTP/1.1" 200 OK

How do I get the time stamp along with the request logging?如何获取时间戳以及请求记录? Like:喜欢:

INFO:     "2020-07-16:23:34:78" - 122.179.31.158:54604 - "GET /api/hello_world?num1=5&num2=10 HTTP/1.1" 200 OK

You can create a dict logger config and initialize the same using dictConfig function in your main application.您可以在主应用程序中创建一个dict 记录器配置并使用dictConfig function 对其进行初始化。

#main.py

from logging.config import dictConfig from config import log_config

from fastapi import FastAPI

dictConfig(log_config.sample_logger)

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

#config/log_config.py

sample_logger = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "access": {
            "()": "uvicorn.logging.AccessFormatter",
            "fmt": '%(levelprefix)s %(asctime)s :: %(client_addr)s - "%(request_line)s" %(status_code)s',
            "use_colors": True
        },
    },
    "handlers": {
        "access": {
            "formatter": "access",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stdout",
        },
    },
    "loggers": {
        "uvicorn.access": {
            "handlers": ["access"],
            "level": "INFO",
            "propagate": False
        },
    },
}

You can use Uvicorn's LOGGING_CONFIG你可以使用 Uvicorn 的LOGGING_CONFIG

import uvicorn
from uvicorn.config import LOGGING_CONFIG
from fastapi import FastAPI

app = FastAPI()

def run():
    LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s [%(name)s] %(levelprefix)s %(message)s"
    uvicorn.run(app)

if __name__ == '__main__':
    run()

Which will return uvicorn log with the timestamp这将返回带有时间戳的 uvicorn 日志

2020-08-20 02:33:53,765 [uvicorn.error] INFO:     Started server process [107131]
2020-08-20 02:33:53,765 [uvicorn.error] INFO:     Waiting for application startup.
2020-08-20 02:33:53,765 [uvicorn.error] INFO:     Application startup complete.
2020-08-20 02:33:53,767 [uvicorn.error] INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

Was able to achieve the same by not running the server from terminal using uvicorn command.能够通过不使用 uvicorn 命令从终端运行服务器来实现相同的目的。 But by running the server using run function of uvicorn package.但是通过使用运行 uvicorn package 的 function 运行服务器。

While surfing the web for the solution, I ended up on this issue , where Dylan Anthony has written the solution using run function of uvicorn package.在浏览 web 以获得解决方案时,我最终解决了这个问题Dylan Anthony使用运行 function of uvicorn ZEFE90A8E604A7C840E88D03A67ZF6 编写了解决方案。

Although, it will still be good to know how to achieve the same using uvicorn command.虽然,知道如何使用 uvicorn 命令实现同样的效果仍然很好。

Combined the answers of @Yagiz Degirmenci and @HappyFace, I got this code.结合@Yagiz Degirmenci 和@HappyFace 的答案,我得到了这段代码。

LOGGING_CONFIG["formatters"]["default"]["fmt"] = "%(asctime)s [%(name)s] %(levelprefix)s %(message)s"
LOGGING_CONFIG["formatters"]["access"][
    "fmt"] = '%(asctime)s [%(name)s] %(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s'

The log likes this:日志是这样的:

2021-03-31 18:38:22,728 [uvicorn.error] INFO:     Started server process [21824]
2021-03-31 18:38:22,729 [uvicorn.error] INFO:     Waiting for application startup.
2021-03-31 18:38:22,729 [uvicorn.error] INFO:     Application startup complete.
2021-03-31 18:38:22,729 [uvicorn.error] INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
2021-03-31 18:38:26,359 [uvicorn.access] INFO:     127.0.0.1:51932 - "POST /limit HTTP/1.1" 200 OK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM