What are Views?
Views are functions that match instruments and return customizedStream configurations. They enable you to:
- Rename metrics
- Change units
- Customize aggregation
- Filter attributes
- Set cardinality limits
- Drop unwanted metrics
View Trait
&Instrument and returns Option<Stream>.
Instrument Reference
TheInstrument type provides information for matching:
Stream Configuration
TheStream type defines how an instrument’s data should be collected:
Registering Views
Register views when building theMeterProvider:
Common View Patterns
Renaming Metrics
Change metric names without modifying code:Changing Aggregation
Customize how metrics are aggregated:Setting Cardinality Limits
Limit the number of unique attribute combinations:Dropping Metrics
Exclude specific metrics from export:Complete Example
From themetrics-advanced example:
Aggregation Types
Views can specify different aggregation strategies:Default Aggregation
Use the instrument’s default aggregation:Sum Aggregation
Sum all values:LastValue Aggregation
Keep only the last value:Explicit Bucket Histogram
Histogram with custom boundaries:Exponential Histogram
Histogram with exponentially growing buckets:Exponential histograms automatically adjust bucket widths, making them ideal for unpredictable value ranges (e.g., network latency with occasional outliers).
Drop Aggregation
Discard all data:Exponential Histogram Details
Exponential histograms are useful when value ranges are unpredictable:max_size: Maximum number of buckets (higher = more memory, better precision)max_scale: Resolution scale from -10 to 20 (higher = finer buckets)record_min_max: Whether to track min and max values
Pattern Matching
Match instruments by different criteria:By Name
By Name Pattern
By Instrument Kind
By Scope
Multiple Views
Register multiple views in order of precedence:Error Handling
Handle invalid stream configurations gracefully:Use Cases
Reduce Cardinality
Limit high-cardinality metrics:Standardize Units
Convert all duration metrics to seconds:Filter Noisy Metrics
Drop verbose debug metrics in production:Best Practices
- Return
Nonefor non-matching instruments: This allows other views to apply - Use
.ok()for graceful errors: Treats invalid configs as non-matching - Order views by specificity: More specific views first, general views last
- Test view configurations: Ensure views apply as expected
- Document view purposes: Explain why each view exists
Next Steps
Instruments
Learn about different instrument types
Histogram
Understand histogram configuration
Meters
Create and configure Meters
Counter
Use Counter instruments