Skip to content

Instantly share code, notes, and snippets.

@philippegirard
Created April 18, 2020 20:17
Show Gist options
  • Save philippegirard/40023a694eca7598ffe8bd8c051e6d0b to your computer and use it in GitHub Desktop.
Save philippegirard/40023a694eca7598ffe8bd8c051e6d0b to your computer and use it in GitHub Desktop.
fastapi logging middleware
@app.middleware("http")
async def log_requests(request: Request, call_next):
idem = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
logger.info(f"rid={idem} start request path={request.url.path}")
start_time = time.time()
response = await call_next(request)
process_time = (time.time() - start_time) * 1000
formatted_process_time = '{0:.2f}'.format(process_time)
logger.info(f"rid={idem} completed_in={formatted_process_time}ms status_code={response.status_code}")
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment