Skip to content

example how to use a gauge #6155

Open
Open
@geraldstanje

Description

hi,

is the following the right way to use a gauge? need some feedback. also when is the WithInt64Callback called - every 10 seconds? how can i reset a gauge to 0 at the very beginning when my app starts up?

package metrics

import (
	"context"
	"sync/atomic"

	"go.opentelemetry.io/otel/metric"
)

// GaugeIfc defines methods for a gauge metric
type GaugeIfc interface {
	// Set sets the gauge value to a specific value
	Set(ctx context.Context, value int64, labels ...MetricLabel)
}

// Gauge struct holds the gauge value
type Gauge struct {
	name  string
	value int64
}

// Set sets the gauge value atomically
func (g *Gauge) Set(_ context.Context, v int64, labels ...MetricLabel) {
	atomic.StoreInt64(&g.value, v)
}

// NewGauge creates a synchronous gauge and registers a callback
func (mh *meterHandle) NewGauge(name, description, unit string) (GaugeIfc, error) {
	// Create an observable gauge instrument
	g := &Gauge{name: name}

	// Register the observable gauge with the meter
	_, err := mh.meter.Int64ObservableGauge(
		name,
		metric.WithDescription(description),
		metric.WithUnit(unit),
		metric.WithInt64Callback(func(ctx context.Context, observer metric.Int64Observer) error {
			// Observe the value and pass it to the observer
			observer.Observe(atomic.LoadInt64(&g.value))
			return nil
		}),
	)
	if err != nil {
		return nil, err
	}

	// Return the Gauge struct
	return g, nil
}

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions