autometrics-dev / autometrics-py

Easily add metrics to your code that actually help you spot and debug issues in production. Built on Prometheus and OpenTelemetry.
https://autometrics.dev
Apache License 2.0
214 stars 7 forks source link

Feature: add integrations for common frameworks like FastAPI #91

Open brettimus opened 11 months ago

brettimus commented 11 months ago

Taking inspiration from the way Strawberry handles integrations with common frameworks.

For instance, they have a package called strawberry-graphql[fastapi], which allows you to import a GraphQLRouter, which you can then use directly with FastAPI as follows (docs here):


import strawberry

from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter

@strawberry.type
class Query:
    @strawberry.field
    def hello(self) -> str:
        return "Hello World"

schema = strawberry.Schema(Query)

graphql_app = GraphQLRouter(schema)

app = FastAPI()
app.include_router(graphql_app, prefix="/graphql")

I could imagine something similar for autometrics-py, which allows you to do the following

import strawberry

from fastapi import FastAPI
# NOTE - you'll need to `pip install 'autometrics[fastapi]` to use `MetricsRouter`
from autometrics.fastapi import MetricsRouter

metrics_app = MetricsRouter()

app = FastAPI()
app.include_router(metrics_app, prefix="/metrics")

Effectively, this MetricsRouter would be sugar for

from prometheus_client import generate_latest

# Set up a metrics endpoint for Prometheus to scrape
#   `generate_latest` returns metrics data in the Prometheus text format
@app.get("/metrics")
def metrics():
    return Response(generate_latest())