Export metrics to Prometheus using OTLP - the recommended approach for Prometheus integration
The dedicated opentelemetry-prometheus crate has been discontinued as of version 0.29. It depends on an unmaintained protobuf crate with known security vulnerabilities.
For Prometheus integration, use the OTLP exporter instead. Prometheus natively supports the OTLP protocol, providing a more stable, secure, and actively maintained solution.
use opentelemetry::global;use opentelemetry::KeyValue;use opentelemetry_otlp::{MetricExporter, Protocol, WithExportConfig};use opentelemetry_sdk::metrics::SdkMeterProvider;use opentelemetry_sdk::Resource;use std::time::Duration;#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> { // Initialize meter provider let exporter = MetricExporter::builder() .with_http() .with_protocol(Protocol::HttpBinary) .with_endpoint("http://localhost:9090/api/v1/otlp/v1/metrics") .build()?; let meter_provider = SdkMeterProvider::builder() .with_periodic_exporter(exporter) .with_resource( Resource::builder() .with_service_name("metrics-demo") .build() ) .build(); global::set_meter_provider(meter_provider.clone()); let meter = global::meter("example-meter"); // Counter - monotonically increasing value let request_counter = meter .u64_counter("http_requests_total") .with_description("Total number of HTTP requests") .with_unit("requests") .build(); // Histogram - distribution of values let request_duration = meter .f64_histogram("http_request_duration_seconds") .with_description("HTTP request duration") .with_unit("s") .build(); // Observable Gauge - current value at collection time let active_connections = meter .u64_observable_gauge("active_connections") .with_description("Number of active connections") .with_unit("connections") .build(); // Simulate application metrics for i in 0..10 { // Record requests request_counter.add(1, &[ KeyValue::new("method", "GET"), KeyValue::new("endpoint", "/api/users"), ]); // Record request duration request_duration.record(0.150 + (i as f64 * 0.01), &[ KeyValue::new("method", "GET"), KeyValue::new("status", "200"), ]); tokio::time::sleep(Duration::from_secs(1)).await; } // Shutdown to export final metrics meter_provider.shutdown()?; Ok(())}
This section is for reference only. The prometheus exporter is deprecated and should not be used in new projects.
The old opentelemetry-prometheus crate provided a pull-based exporter that exposed metrics via an HTTP endpoint. This approach is no longer recommended.For pull-based metrics, use the OpenTelemetry Collector with the Prometheus exporter as shown in the Production Deployment section.