Skip to content

feat: add per-field labels support#10

Merged
DaniPopes merged 6 commits intomainfrom
dani/field-labels
Feb 2, 2026
Merged

feat: add per-field labels support#10
DaniPopes merged 6 commits intomainfrom
dani/field-labels

Conversation

@DaniPopes
Copy link
Copy Markdown
Member

Add ability to attach labels to individual struct fields:

#[derive(Metrics)]
#[metrics(scope = "forwarder")]
struct TransactionMetrics {
    #[metric(rename = "transactions", labels = [("outcome", "forwarded")])]
    forwarded: Counter,
    #[metric(rename = "transactions", labels = [("outcome", "dropped")])]
    dropped: Counter,
}

This allows multiple fields to share the same metric name while being distinguished by label values, which renders better in dashboards than separate metric names.

Field-level labels are appended to struct-level labels passed via new_with_labels(), so both can coexist.

Closes #1

Add ability to attach labels to individual struct fields:

    #[derive(Metrics)]
    #[metrics(scope = "forwarder")]
    struct TransactionMetrics {
        #[metric(rename = "transactions", labels = [("outcome", "forwarded")])]
        forwarded_transactions: Counter,
        #[metric(rename = "transactions", labels = [("outcome", "dropped")])]
        dropped_transactions: Counter,
    }

Field-level labels are appended to struct-level labels passed via
new_with_labels().

Closes #1
- Add FieldLabelMetrics and DynamicFieldLabelMetrics test structs
- Add field_labels_static and field_labels_dynamic tests
- Add compile-fail tests for invalid label syntax
Add ability to specify labels at the struct level that apply to all fields:

    #[derive(Metrics)]
    #[metrics(scope = "api", labels = [("service", "gateway")])]
    struct ApiMetrics {
        /// Total requests.
        requests: Counter,
    }

Label order: instance labels (new_with_labels) → global labels → field labels.
Label values can now be constants or other expressions, not just string literals:

    const SERVICE_NAME: &str = "gateway";

    #[derive(Metrics)]
    #[metrics(scope = "api", labels = [("service", SERVICE_NAME)])]
    struct ApiMetrics {
        requests: Counter,
    }

Label keys must still be string literals.
Comment thread src/expand.rs
Error at compile time if the same label key is specified multiple times
within a single labels attribute.
@DaniPopes DaniPopes merged commit 17e1120 into main Feb 2, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: ability to attach labels to individual fields

2 participants