fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

How does fastapi record response time

Open L1uNan opened this issue 3 years ago • 5 comments

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.

L1uNan avatar Jun 05 '21 06:06 L1uNan

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.

aminPial avatar Jun 09 '21 08:06 aminPial

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?

eignerfr avatar Sep 16 '21 12:09 eignerfr

Has any resolution?

so2bin avatar Apr 11 '22 08:04 so2bin

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

LiberiFatali avatar Jul 22 '22 09:07 LiberiFatali

You would need to override the logging produced by Uvicorn. Maybe this blog will give you some idea on how to achieve this.

JarroVGIT avatar Jul 23 '22 11:07 JarroVGIT

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.

kynk94 avatar Feb 24 '23 02:02 kynk94