Skip to content

Commit

Permalink
Add async instrumentation support
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreasPB committed Aug 2, 2021
1 parent 02e807b commit 493ac51
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions prometheus_fastapi_instrumentator/instrumentation.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Copyright © 2020 Tim Schwenke <[email protected]>
# Licensed under Apache License 2.0 <http://www.apache.org/licenses/LICENSE-2.0>

import asyncio
import gzip
import os
import re
from timeit import default_timer
from typing import Callable, List, Optional, Pattern, Tuple
from typing import Callable, List, Optional, Pattern, Tuple, Union, Awaitable

from fastapi import FastAPI
from prometheus_client import Gauge
Expand Down Expand Up @@ -99,6 +99,7 @@ def __init__(
self.excluded_handlers = []

self.instrumentations: List[Callable[[metrics.Info], None]] = []
self.async_instrumentations: List[Callable[[metrics.Info], Awaitable[None]]] = []

# ==========================================================================

Expand Down Expand Up @@ -195,6 +196,10 @@ async def dispatch_middleware(request: Request, call_next) -> Response:
for instrumentation in self.instrumentations:
instrumentation(info)

await asyncio.gather(*[
instrumentation(info) for instrumentation in self.async_instrumentations
])

return response

# ----------------------------------------------------------------------
Expand Down Expand Up @@ -284,7 +289,10 @@ def metrics(request: Request):

# ==========================================================================

def add(self, instrumentation_function: Callable[[metrics.Info], None]):
def add(
self,
instrumentation_function: Callable[[metrics.Info], Union[None, Awaitable[None]]]
) -> 'PrometheusFastApiInstrumentator':
"""Adds function to list of instrumentations.
Args:
Expand All @@ -296,8 +304,10 @@ def add(self, instrumentation_function: Callable[[metrics.Info], None]):
Returns:
self: Instrumentator. Builder Pattern.
"""

self.instrumentations.append(instrumentation_function)
if asyncio.iscoroutinefunction(instrumentation_function):
self.async_instrumentations.append(instrumentation_function)
else:
self.instrumentations.append(instrumentation_function)

return self

Expand Down

0 comments on commit 493ac51

Please sign in to comment.