Metric - Dynamic Attributes Example
Code Source: https://github.com/gogf/examples/tree/main/observability/metric/dynamic_attributes
Description
This example demonstrates how to work with dynamic metric attributes in GoFrame
using OpenTelemetry
and Prometheus
integration. It shows how to:
- Add dynamic attributes to metrics at runtime
- Combine constant and dynamic attributes
- Use attributes in both regular and observable metrics
- Export metrics with dynamic attributes
Structure
- `go.mod`: The Go module file for dependency management
- `go.sum`: The Go module checksums file
- `main.go`: The main application demonstrating dynamic metric attributes
Features
The example showcases the following features:
-
Dynamic Attributes
- Runtime attribute assignment
- Attribute combination
- Value-based attributes
-
Metric Types with Attributes
- Counter with dynamic attributes
- Observable Counter with dynamic attributes
- Constant attribute baseline
-
Attribute Management
- Attribute creation
- Value typing
- Attribute scoping
Requirements
- Go 1.22 or higher
- Git
- GoFrame
- GoFrame OpenTelemetry Metric
Usage
-
Run the example:
go run main.go
-
Access the metrics:
# Using curl
curl http://localhost:8000/metrics
# Or open in browser
http://localhost:8000/metrics -
Example metrics output:
# HELP goframe_metric_demo_counter This is a simple demo for Counter usage
goframe_metric_demo_counter{const_attr_1="1",dynamic_attr_2="2"} 11
# HELP goframe_metric_demo_observable_counter This is a simple demo for ObservableCounter usage
goframe_metric_demo_observable_counter{const_attr_4="4",dynamic_attr_1="1"} 10
Implementation Details
The example demonstrates:
- Creating metrics with constant attributes
- Adding dynamic attributes at runtime
- Combining different attribute types
- Attribute scoping and inheritance
- Proper attribute value typing
Notes
- Dynamic attributes are added per observation
- Constant attributes are always present
- Attributes can be of various types
- Consider cardinality when using dynamic attributes
- High cardinality can impact performance
- Default port is 8000
- Metrics endpoint is at /metrics