'Uvicorn/FastAPI Duplicate Logging
My FastAPI app seems to log many things twice.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [21360] using statreload
INFO: Started server process [21362]
INFO:uvicorn.error:Started server process [21362]
INFO: Waiting for application startup.
INFO:uvicorn.error:Waiting for application startup.
INFO: Application startup complete.
INFO:uvicorn.error:Application startup complete.
^CINFO: Shutting down
INFO:uvicorn.error:Shutting down
INFO: Waiting for application shutdown.
INFO:uvicorn.error:Waiting for application shutdown.
INFO: Application shutdown complete.
INFO:uvicorn.error:Application shutdown complete.
INFO: Finished server process [21362]
INFO:uvicorn.error:Finished server process [21362]
INFO: Stopping reloader process [21360]
This includes any exceptions that are raised, you get the entire stack trace twice. I've seen some answers suggest just removing the log handlers for Uvicorn, but this feels wrong. What if there is a logging event that happens at the Uvicorn layer of the stack but not in FastAPI?
Is there a way to get only log output once without just overwriting uvicorn's log handlers?
Solution 1:[1]
FastAPI doesn't do much logging. How you run fastapi, with gunicorn or without it? ~~From the info you given, it's not enough to tell where the duplicate comes from.~~ But anyway, we still could get a solution.
uvicorn.error is the internal logger used by uvicorn for error msg. propagate is the default behavior of this logger. One of the duplicate line must be from handler on uvicorn.error, the other is from upper/parent logger.
The solution is to stop msg handled by two logger.
Stop setting up handler for parent logger (probably
rootlogger)Or Disable
uvicorn.errorpropagating.logger = logging.getLogger("uvicorn.error") logger.propagate = False
This shouldn't be a problem when running gunicorn + uvicorn with UvicornWorker, when you're using the latest version of uvicorn.
Solution 2:[2]
Also in case it helps someone, this page is very helpful. Furthermore, I had an issue where SQLAlchemy was getting initialized after setup_logging() from that code was called. Once I changed it to get initialized immediately, my duplicate logs were removed.
Solution 3:[3]
A bit late but this works for me.
I wanted to remove the default logging done by uvicorn and use my custom logger.
logging.getLogger("uvicorn").removeHandler(logging.getLogger("uvicorn").handlers[0])
Make sure that you haven't turned off propagation of logs as mentioned in above answer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Dan Diephouse |
| Solution 3 | Ankit Jain |
