|
| 1 | +from opentelemetry import trace |
| 2 | +from autometrics import autometrics |
| 3 | +from prometheus_client import REGISTRY |
| 4 | +from prometheus_client.openmetrics.exposition import generate_latest |
| 5 | +from starlette import applications |
| 6 | +from starlette.responses import PlainTextResponse |
| 7 | +from starlette.routing import Route |
| 8 | +from opentelemetry import trace |
| 9 | +from opentelemetry.sdk.trace import TracerProvider |
| 10 | +from opentelemetry.sdk.trace.export import ( |
| 11 | + BatchSpanProcessor, |
| 12 | + ConsoleSpanExporter, |
| 13 | +) |
| 14 | + |
| 15 | +# Let's start by setting up the OpenTelemetry SDK with some defaults |
| 16 | +provider = TracerProvider() |
| 17 | +processor = BatchSpanProcessor(ConsoleSpanExporter()) |
| 18 | +provider.add_span_processor(processor) |
| 19 | +trace.set_tracer_provider(provider) |
| 20 | + |
| 21 | +# Now we can instrument our Starlette application |
| 22 | +tracer = trace.get_tracer(__name__) |
| 23 | + |
| 24 | + |
| 25 | +# We need to add tracer decorator before autometrics so that we see the spans |
| 26 | +@tracer.start_as_current_span("request") |
| 27 | +@autometrics |
| 28 | +def outer_function(request): |
| 29 | + response = inner_function() |
| 30 | + return PlainTextResponse(response) |
| 31 | + |
| 32 | + |
| 33 | +# This function will also get an exemplar because it is called within |
| 34 | +# the span of the outer_function |
| 35 | +@autometrics |
| 36 | +def inner_function(): |
| 37 | + return "Hello world!" |
| 38 | + |
| 39 | + |
| 40 | +def metrics(request): |
| 41 | + # Exemplars are not supported by default prometheus format, so we specifically |
| 42 | + # make an endpoint that uses the OpenMetrics format that supoorts exemplars. |
| 43 | + body = generate_latest(REGISTRY) |
| 44 | + return PlainTextResponse(body, media_type="application/openmetrics-text") |
| 45 | + |
| 46 | + |
| 47 | +app = applications.Starlette( |
| 48 | + routes=[Route("/", outer_function), Route("/metrics", metrics)] |
| 49 | +) |
| 50 | + |
| 51 | +# Now, start the app (env variables are required to enable exemplars): |
| 52 | +# AUTOMETRICS_TRACKER=prometheus AUTOMETRICS_EXEMPLARS=true uvicorn starlette-otel-exemplars:app --port 8080 |
| 53 | +# And make some requests to /. You should see the spans in the console. |
| 54 | +# With autometrics extension installed, you can now hover over the hello handler |
| 55 | +# and see the charts and queries associated with them. Open one of the queries |
| 56 | +# in Prometheus and you should see exemplars added to the metrics. Don't forget |
| 57 | +# to click the Show Exemplars button in Prometheus to see them! |
0 commit comments