Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example how to use a gauge #6155

Open
geraldstanje opened this issue Jan 11, 2025 · 0 comments
Open

example how to use a gauge #6155

geraldstanje opened this issue Jan 11, 2025 · 0 comments
Labels
bug Something isn't working

Comments

@geraldstanje
Copy link

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
}
@geraldstanje geraldstanje added the bug Something isn't working label Jan 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant