Record monotonically increasing values with Counter instruments in OpenTelemetry Rust
A Counter is a synchronous instrument that records values that only increase over time. Counters are ideal for tracking totals like request counts, bytes sent, or errors encountered.
use opentelemetry::KeyValue;// Record a simple incrementu64_counter.add(1, &[]);// Record with attributesu64_counter.add( 1, &[ KeyValue::new("method", "GET"), KeyValue::new("status", "200"), KeyValue::new("endpoint", "/api/users"), ],);// Record larger incrementsf64_counter.add(1024.5, &[KeyValue::new("protocol", "http")]);
Each unique combination of attributes creates a separate time series.
Cardinality matters! Each unique attribute combination creates a new time series. Avoid high-cardinality attributes like user IDs or request IDs, as they can cause memory issues and poor query performance.
Counters implement Clone, allowing you to share them across your application:
let counter = meter.u64_counter("requests").build();let counter_clone = counter.clone();// Both reference the same underlying countercounter.add(1, &[]);counter_clone.add(1, &[]);
Clone counters rather than creating duplicates with the same name. Creating multiple counters with the same name can lower SDK performance.
// Use when incrementing inline with your codelet counter = meter.u64_counter("requests").build();fn handle_request() { // Increment as events happen counter.add(1, &[KeyValue::new("endpoint", "/api/users")]);}
If your values can both increase and decrease, use UpDownCounter instead:
let updown_counter = meter.i64_up_down_counter("active_connections") .with_description("Number of active connections") .build();// Can add positive or negative valuesupdown_counter.add(1, &[]); // Connection openedupdown_counter.add(-1, &[]); // Connection closed