### Install Autometrics Go Generator Source: https://docs.autometrics.dev/go/quickstart Install the Autometrics Go command-line generator. This is a one-time setup step. ```shell go install github.com/autometrics-dev/autometrics-go/cmd/autometrics@latest ``` -------------------------------- ### Fastify Server Setup Source: https://docs.autometrics.dev/typescript/setting-up-slos-in-fastify Main entry point for a Fastify application. Sets up basic routes for user management. Ensure Autometrics library is installed for metrics collection. ```typescript import { fastify } from "fastify"; import { handleCreateUser, handleDeleteUser, handleUpdateUser, handleGetAllUsers, handleGetUserById, } from "./routes.js"; const app = fastify({logger: true}); app.get("/users", handleGetAllUsers); app.get("/users/:id", handleGetUserById); app.post("/users", handleCreateUser); app.put("/users/:id", handleUpdateUser); app.delete("/users/:id", handleDeleteUser); const port = 3000 app.listen({port}, (err, address) => { if (err) { app.log.error(err); process.exit(1); } app.log.info(`Server listening on ${address}`); }) ``` -------------------------------- ### Express Server Setup Source: https://docs.autometrics.dev/typescript/setting-up-slos-in-express Sets up a basic Express server with routes for user management. Ensure Autometrics library is installed for metrics collection. ```typescript import express, { Request, Response } from "express"; import { handleCreateUser, handleDeleteUser, handleUpdateUser, handleGetAllUsers, handleGetUserById, } from "./routes.js"; const app = express(); app.get("/users", handleGetAllUsers); app.get("/users/:id", handleGetUserById); app.post("/users", handleCreateUser); app.put("/users/:id", handleUpdateUser); app.delete("/users/:id", handleDeleteUser); app.listen(3000, () => { console.log("Server started on port 3000"); }); ``` -------------------------------- ### Example build_info metric Source: https://docs.autometrics.dev/go/adding-version-information This is an example of a build_info metric with labels for branch, commit, version, and service name. ```text build_info{branch="main",commit="5cc2aa5447907fbf0a7ddd",version="1.0.0",service_name="Billing",repository_url="",repository_provider=""} 1 ``` -------------------------------- ### Start Prometheus and Explorer UI Source: https://docs.autometrics.dev/local-development Start the Prometheus server and Autometrics Explorer UI by running the `am start` command with your metrics endpoints. ```shell ./am start ``` -------------------------------- ### Start Autometrics Explorer CLI Source: https://docs.autometrics.dev/python/quickstart Install and start the Autometrics Explorer CLI to locally preview and validate your metrics. It automatically runs Prometheus. ```shell brew install autometrics-dev/tap/am am start ``` -------------------------------- ### Install Autometrics CLI Source: https://docs.autometrics.dev/typescript/quickstart Install the Autometrics CLI using Homebrew. This tool is used to start a local Prometheus instance and view metrics. ```shell brew install autometrics-dev/tap/am am start ``` -------------------------------- ### Install Prometheus with Homebrew Source: https://docs.autometrics.dev/deploying-prometheus/local Use Homebrew to install the Prometheus monitoring system on macOS. ```bash brew install prometheus ``` -------------------------------- ### Install Autometrics Source: https://docs.autometrics.dev/typescript/quickstart Install the Autometrics library using npm. This is the first step to instrumenting your TypeScript code. ```bash npm install @autometrics/autometrics ``` -------------------------------- ### Run Prometheus with Configuration File Source: https://docs.autometrics.dev/deploying-prometheus/local Starts the Prometheus server using the specified configuration file. ```bash prometheus --config.file=prometheus.yml ``` -------------------------------- ### Autometrics TOML Configuration Example Source: https://docs.autometrics.dev/local-development Example `am.toml` file demonstrating various configuration options, including enabling the pushgateway and defining multiple Prometheus scrape endpoints with custom intervals. ```toml pushgateway-enabled = true prometheus-scrape-interval = "1m" [[endpoint]] job-name = "main_app" url = "http://localhost:3030" prometheus-scrape-interval = "5s" [[endpoint]] job-name = "another_app" url = "http://localhost:9090" ``` -------------------------------- ### Autometrics CLI - `am start` Command Source: https://docs.autometrics.dev/local-development/cli-reference Command to start scraping metrics endpoints and provide a web interface for inspection. ```APIDOC ## `am start` Start scraping the specified endpoint(s), while also providing a web interface to inspect the autometrics data **Usage:** `am start [OPTIONS] [METRICS_ENDPOINTS]...` ###### **Arguments:** * `` — The endpoint(s) that Prometheus will scrape. ###### **Options:** * `--prometheus-version ` — The Prometheus version to use. It will be downloaded if am has not downloaded it already Default value: `v2.47.2` * `--scrape-interval ` — The default scrape interval for all Prometheus jobs * `-l`, `--listen-address ` — The listen address for the web server of am Default value: `127.0.0.1:6789` * `-p`, `--pushgateway-enabled ` — Enable pushgateway Possible values: `true`, `false` * `--pushgateway-version ` — The pushgateway version to use Default value: `v1.6.2` * `--static-assets-url ` Default value: `https://explorer.autometrics.dev` * `-d`, `--ephemeral` — Whenever to clean up files created by Prometheus/Pushgateway after successful execution * `--no-rules` — Whenever to _NOT_ load the autometrics rules file into Prometheus * `--scrape-self` — Whenever to instruct Prometheus to scrape this `am` server as well Default value: `false` ``` -------------------------------- ### Install Autometrics Python Library Source: https://docs.autometrics.dev/python/quickstart Install the Autometrics library using pip. This is the first step for any new or existing Python project. ```shell pip install autometrics ``` -------------------------------- ### Install Autometrics CLI with Homebrew Source: https://docs.autometrics.dev/local-development Install the Autometrics CLI using Homebrew on macOS. ```shell brew install autometrics-dev/tap/am ``` -------------------------------- ### Python Build Info Metric Example Source: https://docs.autometrics.dev/python/adding-version-information This metric includes labels for branch, commit, version, service name, repository URL, repository provider, and Autometrics version. Ensure environment variables are set correctly for these labels to be populated. ```text build_info{branch="main",commit="4cfd2f3b26224fa82daf4ba68fe36e188f3153ff",version="1.0.0",service_name="api",repo_url="https://github.com/autometrics-dev/autometrics-rs",repo_provider="github",autometrics_version="1.0.0"} 1 ``` -------------------------------- ### Start Autometrics Explorer Source: https://docs.autometrics.dev/go/quickstart Start the Autometrics Explorer by providing your application's metrics endpoint. This utility runs Prometheus locally and displays metrics in a web UI. ```shell am start ``` -------------------------------- ### Initialize Prometheus Exporter Source: https://docs.autometrics.dev/rust/quickstart Initialize the prometheus_exporter in your main function to start collecting metrics. ```rust use autometrics::prometheus_exporter; pub fn main() { prometheus_exporter::init(); // ... } ``` -------------------------------- ### Run Prometheus Container Source: https://docs.autometrics.dev/deploying-prometheus/docker Start a Prometheus container using Docker, mapping the configuration file and exposing the Prometheus UI port. Ensure Docker is running. ```bash docker run \ -p 9090:9090 \ -v prometheus.yml:/etc/prometheus/prometheus.yml \ prom/prometheus ``` -------------------------------- ### Install TypeScript Plugin for IDE Source: https://docs.autometrics.dev/typescript/quickstart Install the Autometrics TypeScript plugin as a development dependency. This enables IDE features like metric query tooltips. ```bash npm install @autometrics/typescript-plugin --save-dev ``` -------------------------------- ### Axum API with User Management Routes Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum This Rust code sets up a basic Axum web server with routes for CRUD operations on users. It includes handlers for getting all users, getting a user by ID, creating, updating, and deleting users. Autometrics can be integrated without modifying these handler implementations. ```rust use axum::extract::Path; use axum::routing::{delete, post, put}; use axum::Json; use axum::{http::StatusCode, response::IntoResponse, routing::get, Router}; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; #[derive(Serialize, Deserialize, Debug)] struct User { name: String, email: String, } #[tokio::main] async fn main() { let app = Router::new() .route("/users", get(get_all_users)) .route("/users/:id", get(get_user_by_id)) .route("/users", post(create_user)) .route("/users/:id", put(update_user)) .route("/users/:id", delete(delete_user)) let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); } async fn get_all_users() -> impl IntoResponse { // fetch all the users // for now we just return an empty array vec![] } async fn get_user_by_id(Path(_id): Path) -> impl IntoResponse { // Find user by id and return object // For now we just create a User object and return it as JSON let user = User { name: "foo".to_string(), email: "foo@bar.xyz".to_string(), }; (StatusCode::OK, Json(user)) } async fn create_user(Json(user): Json) -> impl IntoResponse { let user = User { name: user.name, email: user.email, }; // do something with User object (StatusCode::CREATED, Json(user)) } async fn update_user(Path(_id): Path) -> impl IntoResponse { // update user based on id StatusCode::OK } async fn delete_user(Path(_id): Path) -> impl IntoResponse { // delete user based on id StatusCode::OK } ``` -------------------------------- ### Install Prometheus Exporter Source: https://docs.autometrics.dev/typescript/quickstart Install the Prometheus exporter package using npm. This package is required for exporting metrics to a Prometheus endpoint. ```bash npm install @autometrics/exporter-prometheus ``` -------------------------------- ### Monorepo Configuration for `rust-roots` Source: https://docs.autometrics.dev/ci-cd Example of configuring the `rust-roots` input for the `diff-metrics` action in a monorepo structure. This allows the action to identify multiple Rust projects within the repository. ```yaml uses: autometrics-dev/diff-metrics@v1 with: gh-token: ${{ secrets.GITHUB_TOKEN }} rust-roots: | project-a project-b project-c ``` -------------------------------- ### Run Prometheus with Persistent Volume Source: https://docs.autometrics.dev/deploying-prometheus/docker Start the Prometheus container, mounting both the configuration file and the persistent data volume. This ensures data is retained across container restarts. ```bash docker run \ -p 9090:9090 \ -v prometheus-data:/prometheus \ -v prometheus.yml:/etc/prometheus/prometheus.yml \ prom/prometheus ``` -------------------------------- ### Run Alertmanager Docker Image Source: https://docs.autometrics.dev/deploying-alertmanager/docker Starts the Alertmanager Docker container, exposing its UI on port 9093 and mounting the custom configuration file. This command assumes `alertmanager.yml` is in the current directory. ```bash docker run \ -p 9093:9093 \ -v $(pwd)/alertmanager.yml:/etc/alertmanager/alertmanager.yml \ prom/alertmanager:latest ``` -------------------------------- ### Deploy Prometheus using Helm Source: https://docs.autometrics.dev/deploying-prometheus/kubernetes Installs the kube-prometheus-stack Helm chart to deploy Prometheus, Alertmanager, and Node Exporter to your Kubernetes cluster. ```bash helm install prometheus prometheus-community/kube-prometheus-stack --namespace monitoring ``` -------------------------------- ### Complete Rust Application with SLOs Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum A full example of a Rust web application using Axum and Autometrics, including SLO definitions and their application to various HTTP handlers. ```rust use autometrics::objectives::{Objective, ObjectiveLatency, ObjectivePercentile}; use autometrics::{autometrics, prometheus_exporter}; use axum::extract::Path; use axum::routing::{delete, post, put}; use axum::Json; use axum::{http::StatusCode, response::IntoResponse, routing::get, Router}; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; #[derive(Serialize, Deserialize, Debug)] struct User { name: String, email: String, } const API_SLO: Objective = Objective::new("api") .success_rate(ObjectivePercentile::P99) .latency(ObjectiveLatency::Ms250, ObjectivePercentile::P99_9); #[tokio::main] async fn main() { let app = Router::new() .route("/users", get(get_all_users)) .route("/users/:id", get(get_user_by_id)) .route("/users", post(create_user)) .route("/users/:id", put(update_user)) .route("/users/:id", delete(delete_user)) .route( "/metrics", get(|| async { prometheus_exporter::encode_http_response() }), ); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); } #[autometrics(objective = API_SLO)] async fn get_all_users() -> impl IntoResponse { // fetch all the users // for now we just return an empty array vec![] } #[autometrics(objective = API_SLO)] async fn get_user_by_id(Path(_id): Path) -> impl IntoResponse { // Find user by id and return object // For now we just create a User object and return it as JSON let user = User { name: "foo".to_string(), email: "foo@bar.xyz".to_string(), }; (StatusCode::OK, Json(user)) } #[autometrics(objective = API_SLO)] async fn create_user(Json(user): Json) -> impl IntoResponse { let user = User { name: user.name, email: user.email, }; // do something with User object (StatusCode::CREATED, Json(user)) } #[autometrics(objective = API_SLO)] async fn update_user(Path(_id): Path) -> impl IntoResponse { // update user based on id StatusCode::OK } #[autometrics(objective = API_SLO)] async fn delete_user(Path(_id): Path) -> impl IntoResponse { // delete user based on id StatusCode::OK } ``` -------------------------------- ### Complete Axum Application with Autometrics Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum This is the complete `main.rs` file demonstrating the integration of Autometrics with an axum web server. It includes imports, struct definitions, route handlers decorated with `#[autometrics]`, and the main server setup. ```rust use autometrics::{autometrics, prometheus_exporter}; use axum::extract::Path; use axum::routing::{delete, post, put}; use axum::Json; use axum::{http::StatusCode, response::IntoResponse, routing::get, Router}; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; #[derive(Serialize, Deserialize, Debug)] struct User { name: String, email: String, } #[tokio::main] async fn main() { let app = Router::new() .route("/users", get(get_all_users)) .route("/users/:id", get(get_user_by_id)) .route("/users", post(create_user)) .route("/users/:id", put(update_user)) .route("/users/:id", delete(delete_user)) .route( "/metrics", get(|| async { prometheus_exporter::encode_http_response() }), ); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); } #[autometrics] async fn get_all_users() -> impl IntoResponse { // fetch all the users // for now we just return an empty array vec![] } #[autometrics] async fn get_user_by_id(Path(_id): Path) -> impl IntoResponse { // Find user by id and return object // For now we just create a User object and return it as JSON let user = User { name: "foo".to_string(), email: "foo@bar.xyz".to_string(), }; (StatusCode::OK, Json(user)) } #[autometrics] async fn create_user(Json(user): Json) -> impl IntoResponse { let user = User { name: user.name, email: user.email, }; // do something with User object (StatusCode::CREATED, Json(user)) } #[autometrics] async fn update_user(Path(_id): Path) -> impl IntoResponse { // update user based on id StatusCode::OK } #[autometrics] async fn delete_user(Path(_id): Path) -> impl IntoResponse { // delete user based on id StatusCode::OK } ``` -------------------------------- ### Import Autometrics and Prometheus Exporter in Rust Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum Import the `autometrics` macro and `prometheus_exporter` along with other necessary axum and serde components. This setup is required before decorating functions. ```rust use autometrics::{autometrics, prometheus_exporter}; use axum::extract::Path; use axum::routing::{delete, post, put}; use axum::Json; use axum::{http::StatusCode, response::IntoResponse, routing::get, Router}; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; ``` -------------------------------- ### Configure Autometrics for Prometheus Export Source: https://docs.autometrics.dev/python/quickstart Initialize Autometrics to export metrics using the Prometheus Python client. This example configures the exporter to run on port 9464 and sets a service name. ```python from autometrics import autometrics, init init( tracker="prometheus", exporter={ "type": "prometheus", "port": 9464, }, service_name="my-service", ) ``` -------------------------------- ### Initialize Autometrics with Version Info Source: https://docs.autometrics.dev/go/adding-version-information Use autometrics.Init with WithService, WithVersion, WithCommit, and WithBranch options to add version information to your metrics. These options are optional. ```go autometrics.Init( autometrics.WithService(""), autometrics.WithVersion(""), autometrics.WithCommit(""), autometrics.WithBranch(""), ) ``` -------------------------------- ### Generate Documentation and Instrumentation Code Source: https://docs.autometrics.dev/go/quickstart Run 'go generate ./...' to generate documentation and instrumentation code. Optionally set AM_PROMETHEUS_URL to control the base URL for metrics links. ```shell AM_PROMETHEUS_URL=http://localhost:9090/ go generate ./... ``` -------------------------------- ### Configure build.rs with vergen Source: https://docs.autometrics.dev/rust/adding-version-information Use this snippet in your `build.rs` file to configure `vergen` to emit Git SHA and branch information. Ensure `vergen::EmitBuilder` is used to generate the necessary build info. ```rust fn main() { vergen::EmitBuilder::builder() .git_sha(true) .git_branch() .emit() .expect("Unable to generate build info"); } ``` -------------------------------- ### Build Go App with ldflags for Version Info Source: https://docs.autometrics.dev/go/adding-version-information Use go build with ldflags to set the Version, Commit, and Branch variables at build time, incorporating git information. ```shell go build -ldflags "-X main.Version=$(git describe --tags) -X main.Commit=$(git rev-parse HEAD) -X main.Branch=$(git rev-parse --abbrev-ref HEAD)" ``` -------------------------------- ### Autometrics CLI - `am init` Command Source: https://docs.autometrics.dev/local-development/cli-reference Command to interactively create a new `am.toml` configuration file. ```APIDOC ## `am init` Create a new `am.toml` file interactively with sensible defaults **Usage:** `am init [OPTIONS]` ###### **Options:** * `--output ` — Where the file should be outputted to. Defaults to current directory Default value: `./am.toml` * `--force` — Whenever to forcefully override an existing `am.toml` file, if it already exists ``` -------------------------------- ### Create ConfigMap for Autometrics Rules Source: https://docs.autometrics.dev/deploying-prometheus/kubernetes Creates a Kubernetes ConfigMap named 'autometrics-rules' from the downloaded 'autometrics.rules.yml' file, storing it in the 'monitoring' namespace. ```bash kubectl create configmap autometrics-rules --from-file=autometrics.rules.yml --namespace monitoring ``` -------------------------------- ### Import Autometrics Library Source: https://docs.autometrics.dev/typescript/quickstart Import the autometrics function from the installed library into your TypeScript code. This makes the instrumentation function available. ```typescript import { autometrics } from "@autrometrics/autometrics"; ``` -------------------------------- ### Initialize and Expose Metrics with OpenTelemetry and Prometheus Handler Source: https://docs.autometrics.dev/go/quickstart Initialize Autometrics with service, meter name, commit, and version information, and expose metrics via the Prometheus HTTP handler. This is the shortest way to set up metrics exposure. ```go import ( autometrics "github.com/autometrics-dev/autometrics-go/otel/autometrics" "github.com/prometheus/client_golang/prometheus/promhttp" ) func main() { autometrics.Init( autometrics.WithService("web-server"), autometrics.WithMeterName("web-server"), autometrics.WithCommit("anySHA"), autometrics.WithVersion("2.1.37"), ) http.Handle("/metrics", promhttp.Handler()) } ``` -------------------------------- ### Check GOBIN in PATH Source: https://docs.autometrics.dev/go/quickstart Verify that the GOBIN directory is included in your system's PATH environment variable to ensure the autometrics binary is accessible. ```shell echo "$PATH" | grep -q "${GOBIN:-$GOPATH/bin}" && echo "GOBIN in PATH" || echo "GOBIN not in PATH, please add it" GOBIN in PATH ``` -------------------------------- ### Initialize Autometrics Source: https://docs.autometrics.dev/go/quickstart Initialize the Autometrics library in your main function. This is required before using its instrumentation features. ```go autometrics.Init() ``` -------------------------------- ### Autometrics for Get User by ID Handler Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum Instrument the `get_user_by_id` handler with the `autometrics` macro. This function demonstrates fetching a user by ID and returning it as JSON, with metrics automatically collected. ```rust #[autometrics] async fn get_user_by_id(Path(_id): Path) -> impl IntoResponse { // Find user by id and return object // For now we just create a User object and return it as JSON let user = User { name: "foo".to_string(), email: "foo@bar.xyz".to_string(), }; (StatusCode::OK, Json(user)) } ``` -------------------------------- ### Decorate FastAPI Endpoints with Autometrics Source: https://docs.autometrics.dev/python/setting-up-slos-in-fastapi Apply the `@autometrics` decorator to your FastAPI path operation functions to automatically generate metrics. This setup also includes a `/metrics` endpoint for Prometheus to scrape. ```python from autometrics import autometrics from prometheus_client import generate_latest from fastapi import FastAPI, Response app = FastAPI() @app.get("/users") @autometrics async def get_all_users(): # ... @app.get("/users/{id}") @autometrics async def get_user_by_id(id: int): # ... @app.post("/users") @autometrics async def create_user(): # ... @app.put("/users/{id}") @autometrics async def update_user(id: int): # ... @app.delete("/users/{id}") @autometrics async def delete_user(id: int): # ... @app.get("/metrics") def metrics(): return Response(generate_latest()) ``` -------------------------------- ### Initialize Autometrics with Build Variables Source: https://docs.autometrics.dev/go/adding-version-information Pass the declared build variables (Version, Commit, Branch) to the autometrics.Init function using the respective With... options. ```go autometrics.Init( autometrics.WithService("Billing"), autometrics.WithVersion(Version), autometrics.WithCommit(Commit), autometrics.WithBranch(Branch), ) ``` -------------------------------- ### Import Autometrics Library Source: https://docs.autometrics.dev/go/quickstart Import the Autometrics Prometheus client library into your Go application's main entry point. ```go import ( autometrics "github.com/autometrics-dev/autometrics-go/prometheus/autometrics" ) ``` -------------------------------- ### Define Custom Error Recording Logic Source: https://docs.autometrics.dev/typescript/setting-up-slos-in-fastify Use a `recordErrorIf` callback to specify conditions for recording an error based on the function's return value. This example registers an error for HTTP status codes between 400 and 599. ```typescript const recordErrorIf = (res: FastifyReply) => { return res.statusCode >= 400 && res.statusCode <= 599; }; ``` -------------------------------- ### Create Monitoring Namespace with kubectl Source: https://docs.autometrics.dev/deploying-explorer/kubernetes Creates a dedicated namespace named 'monitoring' for Kubernetes resources. This is a recommended practice for organizing monitoring tools. ```bash kubectl create namespace monitoring ``` -------------------------------- ### Apply Kubernetes Configuration with kubectl Source: https://docs.autometrics.dev/deploying-explorer/kubernetes Applies the specified Kubernetes configuration file to your cluster. This command deploys the resources defined in the YAML file. ```bash kubectl apply -f explorer.yaml ``` -------------------------------- ### Set up Axum Router with Metrics Endpoint Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum Configure the axum router to include routes for user management and a `/metrics` endpoint that exposes Prometheus-formatted metrics. Ensure the `prometheus_exporter::encode_http_response()` is used for the metrics route. ```rust #[tokio::main] async fn main() { let app = Router::new() .route("/users", get(get_all_users)) .route("/users/:id", get(get_user_by_id)) .route("/users", post(create_user)) .route("/users/:id", put(update_user)) .route("/users/:id", delete(delete_user)) .route( "/metrics", get(|| async { prometheus_exporter::encode_http_response() }), ); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap(); } ``` -------------------------------- ### Initialize Prometheus Exporter Source: https://docs.autometrics.dev/typescript/quickstart Call the init function from the Prometheus exporter as early as possible in your application's entry point. This sets up the necessary configuration for metric export. ```typescript import { init } from "@autometrics/exporter-prometheus" init() ``` -------------------------------- ### Prometheus Configuration File Source: https://docs.autometrics.dev/deploying-prometheus/docker Define the scrape job for your application, specifying the metrics path and target. Adjust the port to match your application's metrics endpoint. ```yaml scrape_configs: - job_name: my-app-name metrics_path: /metrics static_configs: # Replace the port with the port your /metrics endpoint is running on - targets: ["localhost:3000"] scrape_interval: 15s ``` -------------------------------- ### Slack Application Manifest Source: https://docs.autometrics.dev/deploying-alertmanager/docker Use this manifest to create a basic Slack application with permissions to post chat messages. Ensure the application is added to the desired channels. ```yaml _metadata: major_version: 1 minor_version: 0 display_information: name: Autometrics description: This bot provides a way for our Autometrics slack-app to communicate with the Slack API. long_description: | This bot provides a way for our Autometrics slack-app to communicate with the Slack API. The autometrics slack-app will post messages to a specified channel whenever a alert occurs in your alertmanager (note this requires modifications in your alertmanager configuration). background_color: "#00FFAA" settings: org_deploy_enabled: false socket_mode_enabled: false token_rotation_enabled: false features: app_home: home_tab_enabled: false messages_tab_enabled: false bot_user: display_name: Autometrics always_online: false oauth_config: scopes: bot: - chat:write ``` -------------------------------- ### Autometrics CLI - Main Commands Source: https://docs.autometrics.dev/local-development/cli-reference Overview of the main commands available in the Autometrics CLI. ```APIDOC ## `am` Autometrics Companion CLI app **Usage:** `am [OPTIONS] ` ###### **Subcommands:** * `start` — Start scraping the specified endpoint(s), while also providing a web interface to inspect the autometrics data * `system` — Manage am related system settings. Such as cleaning up downloaded Prometheus, Pushgateway installs * `explore` — Open up the existing Explorer * `proxy` — Use am as a proxy to another prometheus instance * `init` — Create a new `am.toml` file interactively with sensible defaults * `discord` — Open the Fiberplane discord to receive help, send suggestions or discuss various things related to Autometrics and the `am` CLI * `update` — Run the updater * `list` — List the functions in a project * `instrument` — Instrument a project entirely ###### **Options:** * `-v`, `--verbose` — Enable verbose logging. By enabling this you are also able to use RUST_LOG environment variable to change the log levels of other modules * `--config-file ` — Use the following file to define defaults for am ``` -------------------------------- ### Configure Autometrics Push Gateway Source: https://docs.autometrics.dev/typescript/using-wrappers-and-decorators Initialize the Autometrics library in browser environments to push metrics to a specified gateway. Configure the push interval using the `pushInterval` option. ```typescript init({ pushGateway: "" }); ``` -------------------------------- ### Dockerfile for OTel Collector Deployment Source: https://docs.autometrics.dev/deploying-otel-collector/northflank A Dockerfile to build a custom OTel Collector image, layering the configuration file onto the base image. ```dockerfile FROM otel/opentelemetry-collector:latest ADD otel-collector-config.yaml /etc/otelcol/config.yaml ``` -------------------------------- ### Apply SLO to create_user Handler Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum Applies the `API_SLO` to the `create_user` handler, ensuring that metrics related to user creation are collected under the defined SLO. ```rust #[autometrics(objective = API_SLO)] async fn create_user(Json(user): Json) -> impl IntoResponse { let user = User { name: user.name, email: user.email, }; // do something with User object (StatusCode::CREATED, Json(user)) } ``` -------------------------------- ### Download Autometrics Ruleset Source: https://docs.autometrics.dev/deploying-prometheus/kubernetes Fetches the Autometrics alerting ruleset from the official repository using curl and saves it to a local file named 'autometrics.rules.yml'. ```bash curl https://raw.githubusercontent.com/autometrics-dev/autometrics-shared/main/autometrics.rules.yml > autometrics.rules.yml ``` -------------------------------- ### Docker Compose for Slack Application Deployment Source: https://docs.autometrics.dev/deploying-alertmanager/docker This docker-compose.yaml file configures the deployment of the Slack application. Ensure all environment variables, including API tokens and URLs, are correctly set for your environment. ```yaml version: '3.8' services: slack-app: image: autometrics/slack-app:v0.1.0 ports: - "3031:3031" environment: RUST_LOG: info LOG_JSON: "true" LISTEN_HOST: 0.0.0.0 PORT: "3031" BASE_URL: "https://slack-app.example.com" EXPLORER_URL: https://explorer.autometrics.dev SLACK_CHANNEL: "test-slack-app" SLACK_BOT_TOKEN: xoxb-000000000-000000000-000000000 PROMETHEUS_URL: http://prometheus:9090 STORAGE_DIR: /data/ DB_CONNECTION_STRING: "sqlite:///data/slack-app.db?mode=rwc" volumes: - slack-app-data:/data volumes: slack-app-data: ``` -------------------------------- ### Import Autometrics and Axum Dependencies Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum Imports necessary components from the autometrics and axum crates for building a web service with SLOs. ```rust use autometrics::objectives::{Objective, ObjectiveLatency, ObjectivePercentile}; use autometrics::{autometrics, prometheus_exporter}; use axum::extract::Path; use axum::routing::{delete, post, put}; use axum::Json; use axum::{http::StatusCode, response::IntoResponse, routing::get, Router}; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; //... ``` -------------------------------- ### Import Autometrics Utilities Source: https://docs.autometrics.dev/typescript/setting-up-slos-in-fastify Import necessary utilities like `Objective`, `ObjectiveLatency`, and `ObjectivePercentile` from the `@autometrics/autometrics` library to define SLOs. ```typescript import { autometrics, Objective, ObjectiveLatency, ObjectivePercentile, } from "@autometrics/autometrics"; import { fastify } from "fastify"; // ... ``` -------------------------------- ### Configure Prometheus Scraping in fly.toml Source: https://docs.autometrics.dev/deploying-prometheus/fly-io Add this configuration to your `fly.toml` file to enable Fly's Prometheus instance to scrape metrics from your application. Ensure the port and path match your application's metrics endpoint. ```toml app = "your-app-name" [metrics] port = 9091 # default for most prometheus clients path = "/metrics" # default for most prometheus clients ``` -------------------------------- ### Declare Variables for Build Information Source: https://docs.autometrics.dev/go/adding-version-information Declare variables to hold version, commit, and branch information. These can be set at build time using ldflags. ```go var ( Version = "development" Commit = "n/a" Branch string ) ``` -------------------------------- ### Add vergen to Cargo.toml Source: https://docs.autometrics.dev/rust/adding-version-information Add the `vergen` crate with `git` and `gitcl` features to your `Cargo.toml` file to enable Git-related build information. ```toml [build-dependencies] vergen = { version = "8.1", features = ["git", "gitcl"] } ``` -------------------------------- ### Dockerfile for OTel Collector Deployment Source: https://docs.autometrics.dev/deploying-otel-collector/railway A Dockerfile to build an image for the OpenTelemetry Collector. It uses the official collector image and adds a custom configuration file. ```dockerfile FROM otel/opentelemetry-collector:latest ADD otel-collector-config.yaml /etc/otelcol/config.yaml ``` -------------------------------- ### Autometrics CLI - `am explore` Command Source: https://docs.autometrics.dev/local-development/cli-reference Command to open the Autometrics Explorer to visualize metrics. ```APIDOC ## `am explore` Open up the existing Explorer **Usage:** `am explore [OPTIONS]` ###### **Options:** * `--prometheus-endpoint ` — The Prometheus endpoint that will be passed to Explorer * `--explorer-endpoint ` — Which endpoint to open in the browser Default value: `https://explorer.autometrics.dev/` ``` -------------------------------- ### Autometrics CLI - `am list` Commands Source: https://docs.autometrics.dev/local-development/cli-reference Commands for listing functions within a project. ```APIDOC ## `am list` List the functions in a project **Usage:** `am list ` ###### **Subcommands:** * `single` — List functions in a single project, giving the language implementation * `all` — List functions in all projects under the given directory, detecting languages on a best-effort basis ## `am list single` List functions in a single project, giving the language implementation **Usage:** `am list single [OPTIONS] --language ` ``` -------------------------------- ### Dockerfile for Prometheus Source: https://docs.autometrics.dev/deploying-prometheus/railway A Dockerfile to build a Prometheus image. It uses the official Prometheus image, adds a custom configuration file, exposes the Prometheus port, and runs as root to ensure proper volume access. ```dockerfile FROM prom/prometheus:latest ADD prometheus.yml /etc/prometheus/ EXPOSE 9090 USER root ``` -------------------------------- ### Kubernetes Deployment Manifest for Slack App Source: https://docs.autometrics.dev/deploying-alertmanager/kubernetes Deploy the Slack application as a Kubernetes deployment. Ensure all required environment variables are correctly set for Prometheus, Alertmanager, and Slack API access. The STORAGE_DIR and DB_CONNECTION_STRING require persistent storage. ```yaml --- apiVersion: apps/v1 kind: Deployment metadata: name: slack-app labels: app: slack-app spec: selector: matchLabels: app: slack-app template: metadata: labels: app: slack-app spec: containers: - name: slack-app image: "autometrics/slack-app:latest" imagePullPolicy: Always resources: {} env: - name: RUST_LOG value: "info" - name: LOG_JSON value: "true" - name: LISTEN_HOST value: 0.0.0.0 - name: PORT value: "3031" - name: BASE_URL value: "https://slack-app.example.com" # NOTE: this url should be accessible to Slack API - name: EXPLORER_URL value: https://explorer.autometrics.dev - name: SLACK_CHANNEL value: "test-slack-app" - name: SLACK_BOT_TOKEN value: xoxb-000000000-000000000-000000000 - name: PROMETHEUS_URL value: http://prometheus:9090 - name: STORAGE_DIR value: /data/ - name: DB_CONNECTION_STRING value: "sqlite:///data/slack-app.db?mode=rwc" ports: - containerPort: 3031 volumeMounts: - name: storage-volume mountPath: /data volumes: - name: storage-volume persistentVolumeClaim: claimName: slack-app ``` -------------------------------- ### Autometrics CLI - `am system` Commands Source: https://docs.autometrics.dev/local-development/cli-reference Commands for managing Autometrics CLI system settings, including pruning downloaded binaries. ```APIDOC ## `am system` Manage am related system settings. Such as cleaning up downloaded Prometheus, Pushgateway installs **Usage:** `am system ` ###### **Subcommands:** * `prune` — Delete all locally downloaded binaries ## `am system prune` Delete all locally downloaded binaries **Usage:** `am system prune [OPTIONS]` ###### **Options:** * `-f`, `--force` — Force the cleanup without asking for confirmation Default value: `false` ``` -------------------------------- ### Instrument Go Function with Autometrics Source: https://docs.autometrics.dev/go/adding-alerts-and-slos Use the `//autometrics:inst` directive to instrument a Go function for metrics collection. This is a prerequisite for applying alerts and SLOs. ```go //autometrics:inst func RouteHandler(args interface{}) (err error) { // ... return nil } ``` -------------------------------- ### Run Autometrics Explorer with Docker Source: https://docs.autometrics.dev/deploying-explorer/docker Run the Autometrics Explorer Docker container, providing the Prometheus URL as an environment variable. The Explorer will be available on port 6789. ```bash docker run \ -e PROMETHEUS_URL="" \ autometrics/am-proxy:latest ``` -------------------------------- ### Autometrics for Create User Handler Source: https://docs.autometrics.dev/rust/setting-up-slos-in-axum Apply the `autometrics` macro to the `create_user` handler. This function accepts a JSON payload, creates a User object, and returns it with a CREATED status code, while also generating metrics. ```rust #[autometrics] async fn create_user(Json(user): Json) -> impl IntoResponse { let user = User { name: user.name, email: user.email, }; // do something with User object (StatusCode::CREATED, Json(user)) } ```