[][src]Crate instrumented

Instrumented

instrumented provides an attribute macro that enables instrumentation of functions for use with Prometheus.

This crate is largely based on the log-derive crate, and inspired by the metered crate.

To get started, add the [instrumented_codegen::instrument] proc macro to any function you want to instrument. Have a look in the example directory for a full usage.

Configuring

You can specify the global metrics prefix with the METRICS_PREFIX env var, and provide default labels with the METRICS_LABELS env var, which accepts a command separated list of label=value pairs. For example:

METRICS_PREFIX=myapp
METRICS_LABELS=app=myapp,env=prod,region=us

Example

extern crate instrumented;
extern crate log;
extern crate reqwest;

use instrumented::instrument;

// Logs at warn level with the `special` context.
#[instrument(WARN, ctx = "special")]
fn my_func() {
    use std::{thread, time};
    let ten_millis = time::Duration::from_millis(10);
    thread::sleep(ten_millis);
}

#[derive(Debug)]
pub struct MyError;

// Logs result at info level
#[instrument(INFO)]
fn my_func_with_ok_result() -> Result<String, MyError> {
    use std::{thread, time};
    let ten_millis = time::Duration::from_millis(10);
    thread::sleep(ten_millis);

    Ok(String::from("hello world"))
}

// Logs result at debug level
#[instrument(DEBUG)]
fn my_func_with_err_result() -> Result<String, MyError> {
    use std::{thread, time};
    let ten_millis = time::Duration::from_millis(10);
    thread::sleep(ten_millis);

    Err(MyError)
}

fn main() {
    let addr = "127.0.0.1:5000".to_string();
    instrumented::init(&addr);

    my_func();
    assert_eq!(my_func_with_ok_result().is_ok(), true);
    assert_eq!(my_func_with_err_result().is_err(), true);

    let body = reqwest::get(&format!("http://{}/metrics", addr))
        .unwrap()
        .text()
        .unwrap();

    println!("{}", body);
}

Re-exports

pub use instrumented_codegen::instrument;

Modules

prometheus

rust-prometheus crate

Functions

init

Initializes the metrics context, and starts an HTTP server to serve metrics.

register

Register a collector with the global registry.