Skip to main content
Version: 2.8.x(Latest)

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:

  1. Callback-based Metrics

    • Automatic value updates
    • Custom callback functions
    • No manual update needed
  2. Regular Metrics

    • Manual value updates
    • Direct control over values
    • Comparison with callback approach
  3. Metric Configuration

    • Custom attributes
    • Help text
    • Units

Requirements

Usage

  1. Run the example:

    go run main.go
  2. Access the metrics:

    # Using curl
    curl http://localhost:8000/metrics

    # Or open in browser
    http://localhost:8000/metrics
  3. 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:

  1. Creating metrics with callback functions
  2. Automatic value updates through callbacks
  3. Comparison between callback and manual updates
  4. Proper metric configuration
  5. 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