prometheus-fastapi-instrumentator icon indicating copy to clipboard operation
prometheus-fastapi-instrumentator copied to clipboard

Default metrics are gone when adding a custom instrumentation

Open stephen-lazarionok opened this issue 1 year ago • 3 comments

Once I add my custom instrumentation the default metrics are gone..

def my_custom_http_instrumentation(cfg) -> Callable[[Info], None]:
    cntr = Counter(
        "my_http_reqs_total",
        "Number of request accepted.",
        [
            "tenant",
            "tenant_version",
            "method",
            "handler",
            "api_user",
            "response_code",
        ],
    )

    def instrumentation(info: Info) -> None:
        ...
        # implementation
       ...

    return instrumentation


instrumentator = Instrumentator(
    should_group_status_codes=False,
    should_ignore_untemplated=True,
    should_respect_env_var=True,
    should_instrument_requests_inprogress=True,
    excluded_handlers=["/metrics"],
    env_var_name="ENABLE_METRICS",
    inprogress_name="inprogress",
    inprogress_labels=True,
)

instrumentator.add(my_custom_http_instrumentation(my_config))
instrumentator.instrument(app)
instrumentator.expose(app, include_in_schema=False, should_gzip=True)

stephen-lazarionok avatar Nov 29 '23 10:11 stephen-lazarionok

https://github.com/trallnag/prometheus-fastapi-instrumentator/blob/b645ccb618ce9cbe8fd935868f359ebbc12ea217/src/prometheus_fastapi_instrumentator/middleware.py#L85

dasshit avatar Dec 05 '23 09:12 dasshit

Following code will resolve your issue

from prometheus_fastapi_instrumentator import metrics


def my_custom_http_instrumentation(cfg) -> Callable[[Info], None]:
    cntr = Counter(
        "my_http_reqs_total",
        "Number of request accepted.",
        [
            "tenant",
            "tenant_version",
            "method",
            "handler",
            "api_user",
            "response_code",
        ],
    )

    def instrumentation(info: Info) -> None:
        ...
        # implementation
       ...

    return instrumentation


instrumentator = Instrumentator(
    should_group_status_codes=False,
    should_ignore_untemplated=True,
    should_respect_env_var=True,
    should_instrument_requests_inprogress=True,
    excluded_handlers=["/metrics"],
    env_var_name="ENABLE_METRICS",
    inprogress_name="inprogress",
    inprogress_labels=True,
)

instrumentator.add(my_custom_http_instrumentation(my_config))
instrumentator.add(metrics.default())
instrumentator.instrument(app)
instrumentator.expose(app, include_in_schema=False, should_gzip=True)

dasshit avatar Dec 05 '23 09:12 dasshit

Thank you so much, I was experiencing this same issue today!.

lucasalvarezlacasa avatar Jan 12 '24 16:01 lucasalvarezlacasa