Timing ASGI

0.3.2 · active · verified Sat Apr 11

Timing-asgi is an ASGI middleware designed to automatically instrument ASGI endpoints and emit timing metrics. Developed by GRID, it's particularly useful for integrating with statsd-based cloud monitoring services like Datadog. The library currently supports ASGI3 and is actively maintained, with version 0.3.2 being the latest release.

Warnings

Install

Imports

Quickstart

This example demonstrates how to integrate `timing-asgi` with a Starlette application. It defines a custom `TimingClient` that prints the collected metrics to the console. The `TimingMiddleware` is added to the Starlette application, configured with the custom client and a `StarletteScopeToName` metric namer to generate meaningful metric names based on the Starlette routes.

import logging
import uvicorn
from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from timing_asgi import TimingMiddleware, TimingClient
from timing_asgi.integrations import StarletteScopeToName


class PrintTimings(TimingClient):
    """A simple TimingClient that prints metrics to stdout."""
    def timing(self, metric_name: str, timing: float, tags: list[str]) -> None:
        print(f"Metric: {metric_name}, Time: {timing:.6f}, Tags: {tags}")


app = Starlette()

@app.route("/")
async def homepage(request):
    return PlainTextResponse("hello world")

app.add_middleware(
    TimingMiddleware,
    client=PrintTimings(),
    metric_namer=StarletteScopeToName(prefix="myapp", starlette_app=app)
)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    print("Running Uvicorn on http://127.0.0.1:8000. Access / to see timing metrics.")
    uvicorn.run(app, host="127.0.0.1", port=8000)

view raw JSON →