#ebpf #telemetry #telemetry-metrics #metrics

aya-metrics

A metrics library for eBPF programs

1 unstable release

new 0.2.0 Mar 27, 2025

#13 in #telemetry-metrics

MIT/Apache

28KB
425 lines

Gets metrics from an eBPF program!

This is a generalized user space implementation to collect custom metrics from an eBPF program.

The module provides the [EbpfMetrics] type, which reads counters created in eBPF and emits them using the [metrics] crate. Any implementation of the metrics::recorder::Recorder trait can be used once it is set as the global recorder.

Example:

Define counters:


#[derive(Copy, Clone)]
enum MyCounter {
    Packets,
    Bytes,
}

impl aya_metrics_common::Counter for MyCounter {
    fn name(self) -> String {
        match self {
            MyCounter::Packets => "packets_counter".to_string(),
            MyCounter::Bytes => "bytes_counter".to_string(),
        }
    }

    fn index(&self) -> u32 {
        match self {
            MyCounter::Packets => 0,
            MyCounter::Bytes => 1,
        }
    }
}

let metrics = vec![
    Metric::new(
        MyCounter::Packets,
        Unit::Count,
        vec![
            Dimension::By(vec![]),
            Dimension::By(vec![Label::new("hostname", "test.hostname")]),
        ]
    )
];

Emit metrics:

# let mut bpf = aya::Ebpf::load(&[]).unwrap();
// start emitting metrics using the global recorder
EbpfMetrics::new(&mut bpf, metrics, Duration::from_secs(60)).unwrap();

With the following eBPF code:

use aya_metrics_common::metrics::{counter, Counter};
use my_crate::MyCounter;

counter(MyCounter::Packets, 1);

Dependencies

~8–17MB
~219K SLoC