metric – go.opentelemetry.io/otel/metric Index | Examples | Files | Directories

package metric

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

Package metric provides the OpenTelemetry API used to measure metrics about source code operation.

This API is separate from its implementation so the instrumentation built from it is reusable. See go.opentelemetry.io/otel/sdk/metric for the official OpenTelemetry implementation of this API.

All measurements made with this package are made via instruments. These instruments are created by a Meter which itself is created by a MeterProvider. Applications need to accept a MeterProvider implementation as a starting point when instrumenting. This can be done directly, or by using the OpenTelemetry global MeterProvider via GetMeterProvider. Using an appropriately named Meter from the accepted MeterProvider, instrumentation can then be built from the Meter's instruments. See go.opentelemetry.io/otel/metric/instrument for documentation on each instrument and its intended use.

Index

Examples

Types

type Callback

type Callback func(context.Context, Observer) error

Callback is a function registered with a Meter that makes observations for the set of instruments it is registered with. The Observer parameter is used to record measurment observations for these instruments.

The function needs to complete in a finite amount of time and the deadline of the passed context is expected to be honored.

The function needs to make unique observations across all registered Callbacks. Meaning, it should not report measurements for an instrument with the same attributes as another Callback will report.

The function needs to be concurrent safe.

type Meter

type Meter interface {
	// Int64Counter returns a new instrument identified by name and configured
	// with options. The instrument is used to synchronously record increasing
	// int64 measurements during a computational operation.
	Int64Counter(name string, options ...instrument.Int64CounterOption) (instrument.Int64Counter, error)
	// Int64UpDownCounter returns a new instrument identified by name and
	// configured with options. The instrument is used to synchronously record
	// int64 measurements during a computational operation.
	Int64UpDownCounter(name string, options ...instrument.Int64UpDownCounterOption) (instrument.Int64UpDownCounter, error)
	// Int64Histogram returns a new instrument identified by name and
	// configured with options. The instrument is used to synchronously record
	// the distribution of int64 measurements during a computational operation.
	Int64Histogram(name string, options ...instrument.Int64HistogramOption) (instrument.Int64Histogram, error)
	// Int64ObservableCounter returns a new instrument identified by name and
	// configured with options. The instrument is used to asynchronously record
	// increasing int64 measurements once per a measurement collection cycle.
	Int64ObservableCounter(name string, options ...instrument.Int64ObservableCounterOption) (instrument.Int64ObservableCounter, error)
	// Int64ObservableUpDownCounter returns a new instrument identified by name
	// and configured with options. The instrument is used to asynchronously
	// record int64 measurements once per a measurement collection cycle.
	Int64ObservableUpDownCounter(name string, options ...instrument.Int64ObservableUpDownCounterOption) (instrument.Int64ObservableUpDownCounter, error)
	// Int64ObservableGauge returns a new instrument identified by name and
	// configured with options. The instrument is used to asynchronously record
	// instantaneous int64 measurements once per a measurement collection
	// cycle.
	Int64ObservableGauge(name string, options ...instrument.Int64ObservableGaugeOption) (instrument.Int64ObservableGauge, error)

	// Float64Counter returns a new instrument identified by name and
	// configured with options. The instrument is used to synchronously record
	// increasing float64 measurements during a computational operation.
	Float64Counter(name string, options ...instrument.Float64CounterOption) (instrument.Float64Counter, error)
	// Float64UpDownCounter returns a new instrument identified by name and
	// configured with options. The instrument is used to synchronously record
	// float64 measurements during a computational operation.
	Float64UpDownCounter(name string, options ...instrument.Float64UpDownCounterOption) (instrument.Float64UpDownCounter, error)
	// Float64Histogram returns a new instrument identified by name and
	// configured with options. The instrument is used to synchronously record
	// the distribution of float64 measurements during a computational
	// operation.
	Float64Histogram(name string, options ...instrument.Float64HistogramOption) (instrument.Float64Histogram, error)
	// Float64ObservableCounter returns a new instrument identified by name and
	// configured with options. The instrument is used to asynchronously record
	// increasing float64 measurements once per a measurement collection cycle.
	Float64ObservableCounter(name string, options ...instrument.Float64ObservableCounterOption) (instrument.Float64ObservableCounter, error)
	// Float64ObservableUpDownCounter returns a new instrument identified by
	// name and configured with options. The instrument is used to
	// asynchronously record float64 measurements once per a measurement
	// collection cycle.
	Float64ObservableUpDownCounter(name string, options ...instrument.Float64ObservableUpDownCounterOption) (instrument.Float64ObservableUpDownCounter, error)
	// Float64ObservableGauge returns a new instrument identified by name and
	// configured with options. The instrument is used to asynchronously record
	// instantaneous float64 measurements once per a measurement collection
	// cycle.
	Float64ObservableGauge(name string, options ...instrument.Float64ObservableGaugeOption) (instrument.Float64ObservableGauge, error)

	// RegisterCallback registers f to be called during the collection of a
	// measurement cycle.
	//
	// If Unregister of the returned Registration is called, f needs to be
	// unregistered and not called during collection.
	//
	// The instruments f is registered with are the only instruments that f may
	// observe values for.
	//
	// If no instruments are passed, f should not be registered nor called
	// during collection.
	RegisterCallback(f Callback, instruments ...instrument.Observable) (Registration, error)
}

Meter provides access to instrument instances for recording metrics.

Warning: methods may be added to this interface in minor releases.

Example (Asynchronous_multiple)

Code:play 

package main

import (
	"context"
	"fmt"
	"runtime"

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

func main() {
	meterProvider := metric.NewNoopMeterProvider()
	meter := meterProvider.Meter("go.opentelemetry.io/otel/metric#MultiAsyncExample")

	// This is just a sample of memory stats to record from the Memstats
	heapAlloc, _ := meter.Int64ObservableUpDownCounter("heapAllocs")
	gcCount, _ := meter.Int64ObservableCounter("gcCount")
	gcPause, _ := meter.Float64Histogram("gcPause")

	_, err := meter.RegisterCallback(
		func(ctx context.Context, o metric.Observer) error {
			memStats := &runtime.MemStats{}
			// This call does work
			runtime.ReadMemStats(memStats)

			o.ObserveInt64(heapAlloc, int64(memStats.HeapAlloc))
			o.ObserveInt64(gcCount, int64(memStats.NumGC))

			// This function synchronously records the pauses
			computeGCPauses(ctx, gcPause, memStats.PauseNs[:])
			return nil
		},
		heapAlloc,
		gcCount,
	)

	if err != nil {
		fmt.Println("Failed to register callback")
		panic(err)
	}
}

// This is just an example, see the the contrib runtime instrumentation for real implementation.
func computeGCPauses(ctx context.Context, recorder instrument.Float64Histogram, pauseBuff []uint64) {}
Example (Asynchronous_single)

Code:play 

package main

import (
	"context"
	"fmt"

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

func main() {
	// In a library or program this would be provided by otel.GetMeterProvider().
	meterProvider := metric.NewNoopMeterProvider()
	meter := meterProvider.Meter("go.opentelemetry.io/otel/metric#AsyncExample")

	_, err := meter.Int64ObservableGauge(
		"DiskUsage",
		instrument.WithUnit("By"),
		instrument.WithInt64Callback(func(_ context.Context, obsrv instrument.Int64Observer) error {
			// Do the real work here to get the real disk usage. For example,
			//
			//   usage, err := GetDiskUsage(diskID)
			//   if err != nil {
			//   	if retryable(err) {
			//   		// Retry the usage measurement.
			//   	} else {
			//   		return err
			//   	}
			//   }
			//
			// For demonstration purpose, a static value is used here.
			usage := 75000
			obsrv.Observe(int64(usage), attribute.Int("disk.id", 3))
			return nil
		}),
	)
	if err != nil {
		fmt.Println("failed to register instrument")
		panic(err)
	}
}
Example (Synchronous)

Code:play 

package main

import (
	"context"
	"fmt"
	"time"

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

func main() {
	// In a library or program this would be provided by otel.GetMeterProvider().
	meterProvider := metric.NewNoopMeterProvider()

	workDuration, err := meterProvider.Meter("go.opentelemetry.io/otel/metric#SyncExample").Int64Histogram(
		"workDuration",
		instrument.WithUnit("ms"))
	if err != nil {
		fmt.Println("Failed to register instrument")
		panic(err)
	}

	startTime := time.Now()
	ctx := context.Background()
	// Do work
	// ...
	workDuration.Record(ctx, time.Since(startTime).Milliseconds())
}

type MeterConfig

type MeterConfig struct {
	// contains filtered or unexported fields
}

MeterConfig contains options for Meters.

func NewMeterConfig

func NewMeterConfig(opts ...MeterOption) MeterConfig

NewMeterConfig creates a new MeterConfig and applies all the given options.

func (MeterConfig) InstrumentationAttributes

func (cfg MeterConfig) InstrumentationAttributes() attribute.Set

InstrumentationAttributes returns the attributes associated with the library providing instrumentation.

func (MeterConfig) InstrumentationVersion

func (cfg MeterConfig) InstrumentationVersion() string

InstrumentationVersion returns the version of the library providing instrumentation.

func (MeterConfig) SchemaURL

func (cfg MeterConfig) SchemaURL() string

SchemaURL is the schema_url of the library providing instrumentation.

type MeterOption

type MeterOption interface {
	// contains filtered or unexported methods
}

MeterOption is an interface for applying Meter options.

func WithInstrumentationAttributes

func WithInstrumentationAttributes(attr ...attribute.KeyValue) MeterOption

WithInstrumentationAttributes sets the instrumentation attributes.

The passed attributes will be de-duplicated.

func WithInstrumentationVersion

func WithInstrumentationVersion(version string) MeterOption

WithInstrumentationVersion sets the instrumentation version.

func WithSchemaURL

func WithSchemaURL(schemaURL string) MeterOption

WithSchemaURL sets the schema URL.

type MeterProvider

type MeterProvider interface {
	// Meter returns a new Meter with the provided name and configuration.
	//
	// A Meter should be scoped at most to a single package. The name needs to
	// be unique so it does not collide with other names used by
	// an application, nor other applications. To achieve this, the import path
	// of the instrumentation package is recommended to be used as name.
	//
	// If the name is empty, then an implementation defined default name will
	// be used instead.
	Meter(name string, opts ...MeterOption) Meter
}

MeterProvider provides access to named Meter instances, for instrumenting an application or package.

Warning: methods may be added to this interface in minor releases.

func NewNoopMeterProvider

func NewNoopMeterProvider() MeterProvider

NewNoopMeterProvider creates a MeterProvider that does not record any metrics.

type Observer

type Observer interface {
	// ObserveFloat64 records the float64 value with attributes for obsrv.
	ObserveFloat64(obsrv instrument.Float64Observable, value float64, attributes ...attribute.KeyValue)
	// ObserveInt64 records the int64 value with attributes for obsrv.
	ObserveInt64(obsrv instrument.Int64Observable, value int64, attributes ...attribute.KeyValue)
}

Observer records measurements for multiple instruments in a Callback.

type Registration

type Registration interface {
	// Unregister removes the callback registration from a Meter.
	//
	// This method needs to be idempotent and concurrent safe.
	Unregister() error
}

Registration is an token representing the unique registration of a callback for a set of instruments with a Meter.

Source Files

config.go doc.go meter.go noop.go

Directories

PathSynopsis
instrumentPackage instrument provides the OpenTelemetry API instruments used to make measurements.
Version
v1.15.0-rc.2
Published
Mar 23, 2023
Platform
windows/amd64
Imports
3 packages
Last checked
10 minutes ago

Tools for package owners.