Expand description

OpenTelemetry Prometheus Exporter

Prometheus Exporter Example

use opentelemetry::{global, Context, KeyValue, sdk::Resource};
use opentelemetry::sdk::export::metrics::aggregation;
use opentelemetry::sdk::metrics::{controllers, processors, selectors};
use opentelemetry_prometheus::PrometheusExporter;
use prometheus::{TextEncoder, Encoder};

fn init_meter() -> PrometheusExporter {
    let controller = controllers::basic(
        processors::factory(
            selectors::simple::histogram([1.0, 2.0, 5.0, 10.0, 20.0, 50.0]),
            aggregation::cumulative_temporality_selector(),
        )
    )
    .build();

    opentelemetry_prometheus::exporter(controller).init()
}

let cx = Context::current();
let exporter = init_meter();
let meter = global::meter("my-app");

// Use two instruments
let counter = meter
    .u64_counter("a.counter")
    .with_description("Counts things")
    .init();
let recorder = meter
    .i64_histogram("a.histogram")
    .with_description("Records values")
    .init();

counter.add(&cx, 100, &[KeyValue::new("key", "value")]);
recorder.record(&cx, 100, &[KeyValue::new("key", "value")]);

// Encode data as text or protobuf
let encoder = TextEncoder::new();
let metric_families = exporter.registry().gather();
let mut result = Vec::new();
encoder.encode(&metric_families, &mut result);

// result now contains encoded metrics:
//
// # HELP a_counter Counts things
// # TYPE a_counter counter
// a_counter{R="V",key="value",otel_scope_name="my-app",otel_scope_version=""} 100
// # HELP a_histogram Records values
// # TYPE a_histogram histogram
// a_histogram_bucket{R="V",key="value",le="0.5",otel_scope_name="my-app",otel_scope_version=""} 0
// a_histogram_bucket{R="V",key="value",le="0.9",otel_scope_name="my-app",otel_scope_version=""} 0
// a_histogram_bucket{R="V",key="value",le="0.99",otel_scope_name="my-app",otel_scope_version=""} 0
// a_histogram_bucket{R="V",key="value",le="+Inf",otel_scope_name="my-app",otel_scope_version=""} 1
// a_histogram_sum{R="V",key="value",otel_scope_name="my-app",otel_scope_version=""} 100
// a_histogram_count{R="V",key="value",otel_scope_name="my-app",otel_scope_version=""} 1
// HELP otel_scope_info Instrumentation Scope metadata
// TYPE otel_scope_info gauge
// otel_scope_info{otel_scope_name="ex.com/B",otel_scope_version=""} 1

Structs

Traits

  • Encoderprometheus-encoding
    An interface for encoding metric families into an underlying wire protocol.

Functions

  • Create a new prometheus exporter builder.