- add and configure an OpenTelemetry MeterProvider,
- register a metrics reader and exporter,
- create metric instruments (counters, histograms, etc.),
- record metrics from request handlers,
- and validate exports locally (Console exporter) before moving to a production backend such as Prometheus.
/products:
configure_meter() helper. The function:
- creates a metric exporter (ConsoleMetricExporter for local testing),
- creates a metrics reader (PeriodicExportingMetricReader) that periodically exports metrics,
- builds a
MeterProviderwith the reader and aResource, - sets it as the global meter provider,
- and returns a
Meterinstance for creating instruments.
main.py or in a separate module that you import):
| Component | Purpose | Example / Notes |
|---|---|---|
| ConsoleMetricExporter | Sends metric data to stdout for quick local validation | Useful in development; not for production |
| PeriodicExportingMetricReader | Periodically collects and forwards metrics to an exporter | PeriodicExportingMetricReader(exporter, export_interval_millis=5000) |
| MeterProvider | Central provider that manages meters and readers | MeterProvider(metric_readers=[reader], resource=Resource.create({})) |
| Resource | Describes the application/service (attributes like service.name) | Resource.create({}) — replace with attributes as needed |
configure_meter() at application startup, then create instruments from the returned meter. Record metrics inside request handlers.
A compact main.py that includes the configuration and a counter instrument:
Use attributes (labels) on metric recordings to slice metrics by endpoint, HTTP method, status code, or other dimensions. For production, add meaningful
Resource attributes such as service.name, service.version, and environment tags.PeriodicExportingMetricReader will invoke the ConsoleMetricExporter at the configured interval (default 5 seconds). You should see exported metric lines printed to stdout when metrics have been recorded.
Warnings
ConsoleMetricExporter and Flask’s built-in development server are intended for local development and testing only. For production, use a proper exporter (e.g., OTLP or Prometheus exporter) and a production WSGI server such as Gunicorn or uWSGI.
- Add more instruments: histograms for request latency, up-down counters for in-flight requests, or observable instruments.
- Export to production backends:
- Prometheus: use the Prometheus exporter/agent to scrape metrics.
- OTLP: send metrics to an OpenTelemetry Collector and then route to your backend.
- Enrich
Resource.create({})with metadata such as:service.name,service.instance.id,service.version.
- OpenTelemetry Python Metrics: https://opentelemetry.io/docs/instrumentation/python/
- Prometheus: https://prometheus.io
- OpenTelemetry Collector: https://opentelemetry.io/docs/collector/