gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:20:03 30 4
gpt4 key购买 nike

当我使用 uvicorn 运行我的 FastAPI 服务器时:

uvicorn main:app --host 0.0.0.0 --port 8000 --log-level info
运行服务器后得到的日志:
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
如何获取时间戳和请求日志记录?喜欢:
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

最佳答案

您可以创建一个 dict 记录器配置 并使用 dictConfig 对其进行初始化在您的主应用程序中运行。

#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
},
},
}

关于python - 如何在 uvicorn 日志中为每个请求添加时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62934384/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com