Expand description
Proc-macros for idiomatic Prometheus metrics instrumentation
Provides the #[instrument] attribute macro for ergonomic
function instrumentation with counters, histograms, and error tracking.
§Quick Start
Metric names are automatically derived from the function name:
ⓘ
use metrics_helper_macros::instrument;
// Auto-generates metrics:
// - counter: "get_users_total"
// - histogram: "get_users_duration_seconds"
// - error_counter: "get_users_errors_total"
#[instrument]
async fn get_users(method: &str) -> Result<Vec<User>, ApiError> {
// Your code here...
}You can also override specific metric names:
ⓘ
#[instrument(
counter = "http_requests_total", // Override counter name
labels(endpoint = "/users", method),
)]
async fn get_users(method: &str) -> Result<Vec<User>, ApiError> {
// Your code here...
}§Labels
Labels can be either static (fixed values) or dynamic (from function parameters):
§Static Labels
Use key = "value" syntax for labels with fixed values:
ⓘ
#[instrument(labels(service = "api", version = "v1"))]
fn handle() { }§Dynamic Labels (from function parameters)
Use just the parameter name (without a value) to capture it as a label.
The parameter must implement Display:
ⓘ
#[instrument(labels(
table = "users", // static: always "users"
operation, // dynamic: captured from function param
tenant_id, // dynamic: captured from function param
))]
async fn query(operation: &str, tenant_id: &str, limit: usize) -> Result<Data, Error> {
// Metrics will include: table="users", operation=<value>, tenant_id=<value>
}This generates metrics like:
query_total{table="users", operation="select", tenant_id="acme-corp"} 1§Dynamic Labels (from struct fields)
Use dot notation (param.field) to capture struct fields as labels.
The field must implement Display:
ⓘ
struct Request {
method: String,
path: String,
user_id: u64,
}
#[instrument(labels(
service = "api", // static label
request.method, // captures request.method as "method" label
request.path, // captures request.path as "path" label
))]
fn handle_request(request: &Request) {
// Metrics will include: service="api", method=<value>, path=<value>
}You can also specify an explicit key name:
ⓘ
#[instrument(labels(http_method = request.method))]
fn handle(request: &Request) { }Nested field access is also supported:
ⓘ
#[instrument(labels(ctx.request.method))]
fn process(ctx: &Context) { }Attribute Macros§
- instrument
- Attribute macro for instrumenting functions with metrics.