Metric - Basic Example
Code Source: https://github.com/gogf/examples/tree/main/observability/metric/basic
Description
This example demonstrates the basic usage of various metric types in GoFrame
using OpenTelemetry
and Prometheus
integration. It shows how to:
- Create and use different types of metrics
- Configure metric attributes
- Export metrics in
Prometheus
format - Set up a metrics endpoint
Structure
- `go.mod`: The Go module file for dependency management
- `go.sum`: The Go module checksums file
- `main.go`: The main application demonstrating metric usage
Features
The example showcases the following metric types:
-
Counter
- Cumulative measurements
- Only increases
- Used for counting events
-
UpDownCounter
- Bidirectional counter
- Can increase and decrease
- Used for measuring varying quantities
-
Histogram
- Distribution of measurements
- Configurable buckets
- Used for latency/size measurements
-
Observable Metrics
- Counter
- UpDownCounter
- Gauge
- Updated via callbacks
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"} 11
# HELP goframe_metric_demo_histogram This is a simple demo for histogram usage
goframe_metric_demo_histogram_bucket{const_attr_3="3",le="0"} 0
goframe_metric_demo_histogram_bucket{const_attr_3="3",le="10"} 1
...
Implementation Details
The example demonstrates:
- Proper metric initialization and configuration
- Different ways to update metrics
- Attribute handling
Prometheus
integration- Observable metric callbacks
Notes
- Metrics are exported in
Prometheus
format - Default port is 8000
- Metrics endpoint is at /metrics
- All metrics include constant attributes
- Observable metrics are updated via callbacks
- Proper cleanup is handled via defer