Skip to content

Commit 2ba3130

Browse files
committed
properly setup
1 parent 30c4b2f commit 2ba3130

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed

packages/service-library/src/servicelib/fastapi/prometheus_instrumentation.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,20 @@
77

88
def setup_prometheus_instrumentation(app: FastAPI) -> Instrumentator:
99

10-
instrumentator = (
11-
Instrumentator(
12-
should_instrument_requests_inprogress=True, inprogress_labels=False
13-
)
14-
.instrument(app)
15-
.expose(app, include_in_schema=False)
16-
)
17-
18-
def _unregister():
19-
for collector in list(instrumentator.registry._collector_to_names.keys()):
10+
instrumentator = Instrumentator(
11+
should_instrument_requests_inprogress=True, inprogress_labels=False
12+
).instrument(app)
13+
14+
async def on_startup(app: FastAPI) -> None:
15+
instrumentator.expose(app, include_in_schema=False)
16+
17+
def _unregister() -> None:
18+
# NOTE: avoid registering collectors multiple times when running unittests consecutively (https://stackoverflow.com/a/62489287)
19+
for collector in list(
20+
instrumentator.registry._collector_to_names.keys() # noqa: SLF001
21+
):
2022
instrumentator.registry.unregister(collector)
2123

22-
# avoid registering collectors multiple times when running unittests consecutively (https://stackoverflow.com/a/62489287)
24+
app.add_event_handler("startup", on_startup)
2325
app.add_event_handler("shutdown", _unregister)
2426
return instrumentator

0 commit comments

Comments
 (0)