Python

Python小ネタ

小ネタ⑥ uvicornのlogging設定を変更する方法

from typing import Any, Dict
from fastapi import FastAPI
import uvicorn

app = FastAPI()

my_conf: Dict[str, Any] = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "default": {"format": "%(asctime)s:%(name)s:%(levelname)s:%(message)s"}
    },
    "handlers": {
        "default": {
            "formatter": "default",
            "class": "logging.StreamHandler",
            "stream": "ext://sys.stderr"
        }
    },
    "loggers": {
        "uvicorn": {"handlers": ["default"], "level": "INFO"},
    }
}


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}


if __name__ == "__main__":
    config = uvicorn.Config("main:app", port=5000, log_config=my_conf)
    server = uvicorn.Server(config)
    server.run()

コメント

タイトルとURLをコピーしました