Created
April 18, 2020 20:17
-
-
Save philippegirard/40023a694eca7598ffe8bd8c051e6d0b to your computer and use it in GitHub Desktop.
fastapi logging middleware
This file contains hidden or 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
@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