Last active
June 8, 2021 15:02
-
-
Save SyureNyanko/c8855e3fbe68bc5bf880868c772117b5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/63400683/python-logging-with-loguru-log-request-params-on-fastapi-app | |
# https://github.com/tiangolo/fastapi/issues/394 | |
import sys | |
from fastapi import FastAPI, Request | |
from pydantic import BaseModel | |
from typing import List | |
from loguru import logger | |
from starlette.routing import Match | |
from fastapi import FastAPI, APIRouter, Depends | |
from starlette.types import Message | |
logger.remove() | |
logger.add(sys.stdout, colorize=True, | |
format="<green>{time:HH:mm:ss}</green> | {level} | <level>{message}</level>") | |
app = FastAPI() | |
async def set_body(request: Request, body: bytes): | |
async def receive() -> Message: | |
return {"type": "http.request", "body": body} | |
request._receive = receive | |
async def get_body(request: Request) -> bytes: | |
body = await request.body() | |
await set_body(request, body) | |
return body | |
@app.middleware("http") | |
async def log_middle(request: Request, call_next): | |
logger.debug(f"{request.method} {request.url}") | |
routes = request.app.router.routes | |
logger.debug("Params:") | |
for route in routes: | |
match, scope = route.matches(request) | |
if match == Match.FULL: | |
for name, value in scope["path_params"].items(): | |
logger.debug(f"\t{name}: {value}") | |
logger.debug(request.method) | |
logger.debug(await get_body(request)) | |
response = await call_next(request) | |
return response | |
class User(BaseModel): | |
id: int | |
name: str = "Natsumi" | |
@app.post("/user/") | |
def create_user(user: User): | |
return {"res": "ok", "ID": user.id, "名前": user.name} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment