Skip to content

Instantly share code, notes, and snippets.

@SyureNyanko
Last active Jun 8, 2021
Embed
What would you like to do?
# 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