Rust
Quickstart

Getting started in Rust

Here's how to get started with Rust in a new or existing project.

Add Autometrics

Add the autometrics crate dependency using cargo:

cargo add autometrics

Add the Autometrics macro

Add the #[autometrics] macro to the functions you want to instrument with metrics

use autometrics::autometrics;
 
#[autometrics]
pub async fn create_user() {
	// ...
}

Export the metrics

If you're already using Prometheus metrics in your app, you can skip this step. You only need to configure Autometrics to use the same underlying metrics collection library as your existing Prometheus metrics. See Metrics Libraries (opens in a new tab) for more information in the API reference.

Autometrics includes optional functions to help collect and prepare metrics to be scraped by Prometheus. In order to use those, add the prometheus-exporter feature to your autometrics dependency in your Cargo.toml like this:

autometrics = { version = "*", features = ["prometheus-exporter"] }

Then, in your main function, initialize the prometheus_exporter:

use autometrics::prometheus_exporter;
 
pub fn main() {
    prometheus_exporter::init();
    // ...
}

And create a route on your API (probably mounted under /metrics) that returns the following:

use autometrics::prometheus_exporter::{self, PrometheusResponse};
 
/// Export metrics for Prometheus to scrape
pub fn get_metrics() -> PrometheusResponse {
    prometheus_exporter::encode_http_response()
}

You're set! You can now start your app and preview the metrics.

Viewing your metrics

Using Autometrics Explorer

Autometrics Explorer is an open source accompanying utility to preview and validate your metrics locally. It will automatically run Prometheus under the hood for you and show you Autometrics-instrumented functions in a web UI.

See Local Development for more information.

shell
brew install autometrics-dev/tap/am
 
am start <YOUR_APP_METRICS_ENDPOINT>

View your metrics in your IDE or dashboard

You can now navigate your code in your IDE, hover over the instrumented functions and you will see links for generated queries for your metrics.

If you have Grafana you can also import the Autometrics dashboard (opens in a new tab) for an overview and detailed view of the function metrics.

Configure Prometheus to scrape your metrics

Make sure your Prometheus can correctly find the metrics generated by Autometrics. See the Configuring Prometheus section for deploy target-specific instructions.

Example configuration:

scrape_configs:
  - job_name: my-app
    metrics_path: /metrics
    static_configs:
      # Replace the port with the port your app listens on
      - targets: ['localhost:3000']
    # For a real deployment, you would want the scrape interval to be
    # longer but for testing, you want the data to show up quickly
    scrape_interval: 200ms