Rust监控与指标收集库iroh-metrics的使用,提供高性能应用性能数据采集与分析

iroh-metrics

iroh-metrics 是用于 iroh 项目的指标收集库。它提供了必要的"粘合剂"来暴露定义的指标以供收集:一个 HTTP 服务器,可以暴露被跟踪的指标,供 Prometheus 等服务进行轮询记录。

iroh 中的几乎所有指标都记录为简单的计数器。

许可证

本项目采用以下任一许可证:

  • Apache License, Version 2.0
  • MIT license

贡献

除非您明确声明,否则任何有意提交包含在本项目中的贡献,如 Apache-2.0 许可证中所定义的,都将按照上述双重许可,不附加任何额外条款或条件。

安装

在项目目录中运行以下 Cargo 命令:

cargo add iroh-metrics

或在 Cargo.toml 中添加以下行:

iroh-metrics = "0.35.0"

完整示例代码

以下是内容中提供的示例代码:

use iroh_metrics::inc;
use iroh_metrics::core::{Core, Metric};
use std::net::SocketAddr;

// 定义你的指标类型
#[derive(Metric)]
struct MyMetrics {
    // 计数器指标
    requests: Counter,
    // 带有标签的计数器
    errors: CounterVec<&'static str>,
}

// 初始化指标
let metrics = MyMetrics {
    requests: Counter::new("requests_total", "Total number of requests").unwrap(),
    errors: CounterVec::new("errors_total", "Total number of errors", &["type"]).unwrap(),
};

// 注册指标
Core::register(metrics);

// 模拟一些指标更新
inc!(metrics.requests);
inc!(metrics.errors.with_label("timeout"));

// 启动HTTP服务器暴露指标
let addr: SocketAddr = "0.0.0.0:9090".parse().unwrap();
iroh_metrics::serve(addr).expect("Failed to start metrics server");

println!("Metrics server running at http://{}", addr);

这个示例展示了:

  1. 如何定义自定义指标类型
  2. 如何初始化计数器指标
  3. 如何注册指标
  4. 如何更新指标值
  5. 如何启动 HTTP 服务器来暴露指标

扩展完整示例

以下是一个更完整的示例,展示如何在实际应用中使用 iroh-metrics:

use iroh_metrics::{
    inc, dec,
    core::{Core, Metric},
    latency::Histogram
};
use std::net::SocketAddr;
use std::time::Instant;

// 定义应用指标
#[derive(Metric)]
struct AppMetrics {
    // 请求计数器
    http_requests: Counter,
    // 错误计数器(带类型标签)
    http_errors: CounterVec<&'static str>,
    // 请求处理时间直方图(单位:毫秒)
    request_duration: Histogram,
    // 当前活跃连接数
    active_connections: Gauge,
}

impl AppMetrics {
    fn new() -> Self {
        AppMetrics {
            http_requests: Counter::new("http_requests_total", "Total HTTP requests").unwrap(),
            http_errors: CounterVec::new(
                "http_errors_total", 
                "Total HTTP errors by type",
                &["status_code"]
            ).unwrap(),
            request_duration: Histogram::new(
                "http_request_duration_ms",
                "HTTP request duration in milliseconds",
                vec![50.0, 100.0, 200.0, 500.0, 1000.0]
            ).unwrap(),
            active_connections: Gauge::new(
                "active_connections",
                "Current number of active connections"
            ).unwrap(),
        }
    }
}

fn main() {
    // 初始化指标
    let metrics = AppMetrics::new();
    Core::register(metrics);
    
    // 启动指标服务器
    let addr: SocketAddr = "127.0.0.1:9090".parse().unwrap();
    iroh_metrics::serve(addr).expect("Failed to start metrics server");
    
    // 模拟应用行为
    simulate_application(&metrics);
}

fn simulate_application(metrics: &AppMetrics) {
    // 新连接建立
    inc!(metrics.active_connections);
    
    // 处理请求
    let start = Instant::now();
    inc!(metrics.http_requests);
    
    // 模拟请求处理
    std::thread::sleep(std::time::Duration::from_millis(120));
    
    // 记录请求持续时间
    let duration = start.elapsed().as_millis() as f64;
    metrics.request_duration.observe(duration);
    
    // 模拟偶尔出现的错误
    if rand::random::<f32>() > 0.8 {
        inc!(metrics.http_errors.with_label("500"));
    }
    
    // 连接关闭
    dec!(metrics.active_connections);
}

这个扩展示例展示了:

  1. 更复杂的指标类型定义(包括计数器、直方图和量表)
  2. 如何封装指标初始化逻辑
  3. 如何在真实场景中记录请求持续时间和错误
  4. 如何使用带标签的指标
  5. 如何增加和减少量表值

1 回复

iroh-metrics: Rust高性能应用监控与指标收集库

iroh-metrics 是一个用于 Rust 应用的高性能监控和指标收集库,专为需要实时性能数据采集和分析的应用场景设计。

主要特性

  • 轻量级、低开销的指标收集
  • 支持多种指标类型(计数器、计量器、直方图等)
  • 内置 Prometheus 导出器
  • 线程安全的指标操作
  • 可扩展的指标收集架构

完整示例代码

以下是一个完整的示例,展示了如何使用 iroh-metrics 进行指标收集和 Prometheus 导出:

use iroh_metrics::core::{Core, Collector, Metric};
use iroh_metrics::{inc, gauge, histogram, dec};
use std::time::{Instant, Duration};

// 自定义收集器示例
struct SystemMetricsCollector;

impl Collector for SystemMetricsCollector {
    fn collect(&self) -> Vec<Metric> {
        // 模拟收集系统指标
        vec![
            Metric::new("system_thread_count", 8.0)
                .with_label("type", "system")
                .with_help("Number of system threads"),
            Metric::new("system_load_avg", 0.75)
                .with_label("type", "system")
                .with_help("System load average"),
        ]
    }

    fn interval(&self) -> Duration {
        Duration::from_secs(10) // 每10秒收集一次
    }
}

#[tokio::main]
async fn main() {
    // 初始化指标系统
    Core::init(|reg| {
        // 注册自定义指标
        reg.register_metric("http_requests_total", "Total HTTP requests");
        reg.register_metric("memory_usage_bytes", "Memory usage in bytes");
        reg.register_metric("request_duration_seconds", "Request duration in seconds");
        
        // 注册自定义收集器
        reg.register_collector(Box::new(SystemMetricsCollector));
    }).unwrap();

    // 模拟HTTP请求处理
    for i in 0..5 {
        let start = Instant::now();
        
        // 处理请求...
        println!("Processing request {}", i);
        
        // 记录指标
        inc!("http_requests_total");
        gauge!("memory_usage_bytes", 512.0 * (i + 1) as f64);
        
        // 模拟请求处理时间
        std::thread::sleep(Duration::from_millis(100 * (i + 1)));
        let duration = start.elapsed();
        histogram!("request_duration_seconds", duration.as_secs_f64());
    }

    // 启动Prometheus导出器
    println!("Starting Prometheus exporter on :9090");
    iroh_metrics::prometheus_exporter::serve("0.0.0.0:9090").await.unwrap();
}

示例说明

  1. 自定义收集器:实现了 SystemMetricsCollector 来定期收集系统级指标
  2. 指标注册:在初始化时注册了三种类型的指标
  3. 指标记录
    • 使用 inc! 宏记录HTTP请求计数器
    • 使用 gauge! 宏记录内存使用量
    • 使用 histogram! 宏记录请求处理时间
  4. Prometheus导出:最后启动了Prometheus导出服务

运行结果

运行程序后,可以通过 http://localhost:9090/metrics 访问Prometheus格式的指标数据,输出类似:

# HELP http_requests_total Total HTTP requests
# TYPE http_requests_total counter
http_requests_total 5

# HELP memory_usage_bytes Memory usage in bytes
# TYPE memory_usage_bytes gauge
memory_usage_bytes 2560

# HELP request_duration_seconds Request duration in seconds
# TYPE request_duration_seconds histogram
request_duration_seconds_bucket{le="0.1"} 1
request_duration_seconds_bucket{le="0.2"} 2
...
request_duration_seconds_sum 1.5
request_duration_seconds_count 5

# HELP system_thread_count Number of system threads
# TYPE system_thread_count gauge
system_thread_count{type="system"} 8

# HELP system_load_avg System load average
# TYPE system_load_avg gauge
system_load_avg{type="system"} 0.75

这个完整示例展示了 iroh-metrics 的主要功能,包括指标注册、记录、自定义收集和Prometheus导出。

回到顶部