Metric - Callback Example
Code Source: https://github.com/gogf/examples/tree/main/observability/metric/callback
Description
This example demonstrates how to implement callback-based metric collection in GoFrame
using OpenTelemetry
and Prometheus
integration. It shows how to:
- Create metrics with callback functions
- Automatically update metric values through callbacks
- Configure metric attributes
- Export metrics in
Prometheus
format
Structure
- `go.mod`: The Go module file for dependency management
- `go.sum`: The Go module checksums file
- `main.go`: The main application demonstrating callback-based metrics
Features
The example showcases the following features:
-
Callback-based Metrics
- Automatic value updates
- Custom callback functions
- No manual update needed
-
Regular Metrics
- Manual value updates
- Direct control over values
- Comparison with callback approach
-
Metric Configuration
- Custom attributes
- Help text
- Units
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_observable_counter This is a simple demo for ObservableCounter usage
goframe_metric_demo_observable_counter{const_attr_3="3"} 10
Implementation Details
The example demonstrates:
- Creating metrics with callback functions
- Automatic value updates through callbacks
- Comparison between callback and manual updates
- Proper metric configuration
Prometheus
integration
Notes
- Callbacks are executed automatically by the metrics system
- No need for manual updates of callback-based metrics
- Callbacks should be lightweight and fast
- Consider thread safety in callbacks
- Proper cleanup is handled via defer
- Default port is 8000
- Metrics endpoint is at /metrics