prometheus-derive

Crates.ioprometheus-derive
lib.rsprometheus-derive
version0.1.0
created_at2025-08-14 19:11:34.404713+00
updated_at2025-08-14 19:11:34.404713+00
descriptionDerive macros and utilities for prometheus with automatic registration and global registry support
homepage
repositoryhttps://github.com/AlexandreBrg/prometheus-derive
max_upload_size
id1795370
size37,260
Alexandre Burgoni (alexandrebrg)

documentation

README

Prometheus Metrics for Rust

Crates.io MIT/Apache-2.0 Docs.rs

Fast, simple, and type-safe Prometheus metrics for Rust applications.

Define metrics with a single macro. Get automatic registration and type-safe labels. Export to Prometheus format in seconds.

This crate is based on prometheus-client, and aims to provide an interface allowing to have your metrics globally in your application with minimal setup.

Quick Start

Add to your Cargo.toml:

[dependencies]
prometheus-derive = "0.1"
prometheus-client = "0.23"

Define and use metrics:

use prometheus_derive::{prometheus_metrics, GLOBAL_REGISTRY};
use prometheus_client::metrics::{counter::Counter, gauge::Gauge};
use prometheus_client::encoding::text::encode;

// Define metrics with automatic registration
prometheus_metrics! {
    /// Total HTTP requests received  
    #[labels(method = String, status = u16)]
    static HTTP_REQUESTS_TOTAL: Counter;
    
    /// Current active connections
    static ACTIVE_CONNECTIONS: Gauge;
}

fn main() {
    // Use metrics with type-safe labels
    HTTP_REQUESTS_TOTAL
        .get_or_create(&HttpRequestsTotalLabels {
            method: "GET".to_string(),
            status: 200,
        })
        .inc();
    
    ACTIVE_CONNECTIONS.set(42);
    
    // Export for Prometheus scraping
    let mut buffer = String::new();
    let registry = GLOBAL_REGISTRY.read().unwrap();
    encode(&mut buffer, &registry).unwrap();
    println!("{}", buffer);
}

Output:

# HELP HTTP_REQUESTS_TOTAL Total HTTP requests received
# TYPE HTTP_REQUESTS_TOTAL counter
HTTP_REQUESTS_TOTAL{method="GET",status="200"} 1
# HELP ACTIVE_CONNECTIONS Current active connections  
# TYPE ACTIVE_CONNECTIONS gauge
ACTIVE_CONNECTIONS 42

Features

  • Zero-config setup - Works out of the box with global metrics registry
  • Type-safe labels - Generate structs for labeled metrics automatically
  • Full Prometheus compatibility - Based on the official prometheus-client

Examples

Check out the examples/ directory for complete working examples:

  • Web Server - Full Axum web server with metrics endpoint

Architecture

This project consists of two main crates:

  • prometheus-derive - The main crate with the prometheus_metrics! macro and global registry
  • prometheus-derive-macros - Internal procedural macros for code generation

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under either of

at your option.

Related Projects

Commit count: 0

cargo fmt