prometheus-fastapi-instrumentator: the middleware can't be installed for the actual FastAPI version
Hi! Since FastAPI version 0.91.0, I started getting the following error when trying to run the application:
INFO: Will watch for changes in these directories: ['/home/my_name/PycharmProjects/my-app']
INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)
INFO: Started reloader process [15443] using WatchFiles
INFO: Started server process [15472]
INFO: Waiting for application startup.
ERROR: Traceback (most recent call last):
File "/home/my_name/.cache/pypoetry/virtualenvs/my-app-PzElRY_T-py3.10/lib/python3.10/site-packages/starlette/routing.py", line 671, in lifespan
async with self.lifespan_context(app):
File "/home/my_name/.cache/pypoetry/virtualenvs/my-app-PzElRY_T-py3.10/lib/python3.10/site-packages/starlette/routing.py", line 566, in __aenter__
await self._router.startup()
File "/home/my_name/.cache/pypoetry/virtualenvs/my-app-PzElRY_T-py3.10/lib/python3.10/site-packages/starlette/routing.py", line 648, in startup
await handler()
File "/home/my_name/PycharmProjects/my-app/core/app/service.py", line 75, in integrate_monitoring_plugin
Instrumentator(excluded_handlers=["/health", "/metrics"]).instrument(app).expose(app, include_in_schema=False)
File "/home/my_name/.cache/pypoetry/virtualenvs/my-app-PzElRY_T-py3.10/lib/python3.10/site-packages/prometheus_fastapi_instrumentator/instrumentation.py", line 121, in instrument
app.add_middleware(
File "/home/my_name/.cache/pypoetry/virtualenvs/my-app-PzElRY_T-py3.10/lib/python3.10/site-packages/starlette/applications.py", line 135, in add_middleware
raise RuntimeError("Cannot add middleware after an application has started")
RuntimeError: Cannot add middleware after an application has started
ERROR: Application startup failed. Exiting.
I initiate the application this way:
def create_app() -> FastAPI:
app = FastAPI()
#blah-blah-blah
@app.on_event("startup")
async def integrate_monitoring_plugin():
Instrumentator(excluded_handlers=["/health", "/metrics"]).instrument(app).expose(app, include_in_schema=False)
return app
About this issue
- Original URL
- State: closed
- Created a year ago
- Reactions: 11
- Comments: 23 (5 by maintainers)
The
NameError
thing should be fixed now with the latest release https://github.com/trallnag/prometheus-fastapi-instrumentator/releases/tag/v5.11.0can confirm, this works with the new Fastapi
Sure, just a quick note, I’m using
start_http_server
because I run my prometheus server on a diferent port, but I asume you could save the Instrumentator variable and just call.expose
on the startup_event functionThanks.
NameError
is gone.@trallnag thanks for the release. with the new version I started to get another error when running unit tests:
According to the maintainer: