OpenTelemetry Prometheus Exporter

0.61b0 · active · verified Sat Mar 28

The `opentelemetry-exporter-prometheus` library provides a Prometheus Metric Exporter for OpenTelemetry, allowing applications instrumented with OpenTelemetry to expose their metrics in a format that a Prometheus server can scrape. It is part of the larger OpenTelemetry Python project, currently at version 0.61b0, and is under active development with frequent releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry Prometheus Exporter. It initializes a `MeterProvider` with a `PrometheusMetricReader` which automatically starts an HTTP server on port 9464 (by default) that Prometheus can scrape. It then creates a simple counter and increments it periodically, exposing the metric for Prometheus to collect. Remember to set the `OTEL_SERVICE_NAME` environment variable for better metric identification.

import os
import time
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.exporter.prometheus import PrometheusMetricReader
from opentelemetry.sdk.resources import Resource, SERVICE_NAME
from prometheus_client import start_http_server

# Configure the MeterProvider with the PrometheusMetricReader
# PrometheusMetricReader starts an HTTP server, typically on port 9464.
# Ensure this port is available or configure a different one.
reader = PrometheusMetricReader()
provider = MeterProvider(
    resource=Resource.create({
        SERVICE_NAME: os.environ.get('OTEL_SERVICE_NAME', 'my-prometheus-service')
    }),
    metric_readers=[reader]
)
metrics.set_meter_provider(provider)

# Start the Prometheus HTTP server for scraping
# By default, it serves on 0.0.0.0:9464/metrics
start_http_server(port=9464, addr='0.0.0.0')

# Get a meter from the MeterProvider
meter = metrics.get_meter(__name__)

# Create a counter instrument
requests_counter = meter.create_counter(
    name='requests_total',
    description='Total number of requests',
    unit='1'
)

print("Prometheus exporter running on http://localhost:9464/metrics")
print("Press Ctrl+C to exit")

# Simulate work and increment the counter
while True:
    requests_counter.add(1, {"route": "/", "method": "GET"})
    time.sleep(1)

view raw JSON →