fastapi
fastapi copied to clipboard
How does fastapi record response time
How does fastapi record interface response time and reflect it in its own API documents?
Is it possible to display the response time of the interface request on the openapi?
Thank you very much.
Not sure what you actually meant. Do you want to measure the time in between processing a request and then response
? If so then do the following:
# check more on https://fastapi.tiangolo.com/tutorial/middleware/
import time
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
print("Time took to process the request and return response is {} sec".format(time.time() - start_time))
return response
If this is not what you want, please explain a bit more about your query. Cheers.
thanks for the answer. would be cool to have the process time automatically in the log included (for instance in the end: 0.8sec) 2021-09-16 14:53:12,774 - INFO - 127.0.0.1:52962 - "GET / HTTP/1.1" 200 0.8 I'm pretty new to fastapi. I thought it should not be too difficult. Does someone know how to achieve this?
Has any resolution?
thanks for the answer. would be cool to have the process time automatically in the log included (for instance in the end: 0.8sec) 2021-09-16 14:53:12,774 - INFO - 127.0.0.1:52962 - "GET / HTTP/1.1" 200 0.8 I'm pretty new to fastapi. I thought it should not be too difficult. Does someone know how to achieve this?
Could someone share some ideas about this? Thanks
You would need to override the logging produced by Uvicorn. Maybe this blog will give you some idea on how to achieve this.
from uvicorn.config import LOGGING_CONFIG
app = FastAPI(...)
if __name__ == '__main__':
LOGGING_CONFIG["formatters"]["access"]["fmt"] = (
"%(asctime)s " + LOGGING_CONFIG["formatters"]["access"]["fmt"]
)
uvicorn.run('main:app', port=8000, reload=True)
# log
# 2023-02-24 11:01:06,936 INFO: 127.0.0.1:42006 - "GET / HTTP/1.1" 200 OK
Modify LOGGING_CONFIG
in this way.