OpenTelemetry Prometheus Exporter

This library allows export of metrics data to Prometheus.

Usage

The OpenTelemetry Prometheus Exporter allows export of OpenTelemetry metrics to Prometheus.

from opentelemetry import metrics
from opentelemetry.exporter.prometheus import PrometheusMetricsExporter
from opentelemetry.sdk.metrics import Counter, Meter
from prometheus_client import start_http_server

# Start Prometheus client
start_http_server(port=8000, addr="localhost")

# Meter is responsible for creating and recording metrics
metrics.set_meter_provider(MeterProvider())
meter = metrics.get_meter(__name__)
# exporter to export metrics to Prometheus
prefix = "MyAppPrefix"
exporter = PrometheusMetricsExporter(prefix)
# Starts the collect/export pipeline for metrics
metrics.get_meter_provider().start_pipeline(meter, exporter, 5)

counter = meter.create_metric(
    "requests",
    "number of requests",
    "requests",
    int,
    Counter,
    ("environment",),
)

# Labels are used to identify key-values that are associated with a specific
# metric that you want to record. These are useful for pre-aggregation and can
# be used to store custom dimensions pertaining to a metric
labels = {"environment": "staging"}

counter.add(25, labels)
input("Press any key to exit...")

API

class opentelemetry.exporter.prometheus.PrometheusMetricsExporter(prefix='')[source]

Bases: opentelemetry.sdk.metrics.export.MetricsExporter

Prometheus metric exporter for OpenTelemetry.

Parameters

prefix (str) – single-word application prefix relevant to the domain the metric belongs to.

export(metric_records)[source]

Exports a batch of telemetry data.

Parameters

metric_records (Sequence[MetricRecord]) – A sequence of MetricRecord s. A MetricRecord contains the metric to be exported, the labels associated with that metric, as well as the aggregator used to export the current checkpointed value.

Return type

MetricsExportResult

Returns

The result of the export

shutdown()[source]

Shuts down the exporter.

Called when the SDK is shut down.

Return type

None

class opentelemetry.exporter.prometheus.CustomCollector(prefix='')[source]

Bases: object

CustomCollector represents the Prometheus Collector object https://github.com/prometheus/client_python#custom-collectors

add_metrics_data(metric_records)[source]
collect()[source]

Collect fetches the metrics from OpenTelemetry and delivers them as Prometheus Metrics. Collect is invoked every time a prometheus.Gatherer is run for example when the HTTP endpoint is invoked by Prometheus.