metric

package module
v1.25.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 5, 2024 License: Apache-2.0 Imports: 26 Imported by: 641

README

Metric SDK

PkgGoDev

Documentation

Overview

Package metric provides an implementation of the OpenTelemetry metrics SDK.

See https://opentelemetry.io/docs/concepts/signals/metrics/ for information about the concept of OpenTelemetry metrics and https://opentelemetry.io/docs/concepts/components/ for more information about OpenTelemetry SDKs.

The entry point for the metric package is the MeterProvider. It is the object that all API calls use to create Meters, instruments, and ultimately make metric measurements. Also, it is an object that should be used to control the life-cycle (start, flush, and shutdown) of the SDK.

A MeterProvider needs to be configured to export the measured data, this is done by configuring it with a Reader implementation (using the WithReader MeterProviderOption). Readers take two forms: ones that push to an endpoint (NewPeriodicReader), and ones that an endpoint pulls from. See go.opentelemetry.io/otel/exporters for exporters that can be used as or with these Readers.

Each Reader, when registered with the MeterProvider, can be augmented with a View. Views allow users that run OpenTelemetry instrumented code to modify the generated data of that instrumentation.

The data generated by a MeterProvider needs to include information about its origin. A MeterProvider needs to be configured with a Resource, using the WithResource MeterProviderOption, to include this information. This Resource should be used to describe the unique runtime environment instrumented code is being run on. That way when multiple instances of the code are collected at a single endpoint their origin is decipherable.

See go.opentelemetry.io/otel/metric for more information about the metric API.

See go.opentelemetry.io/otel/sdk/metric/internal/x for information about the experimental features.

Example

To enable metrics in your application using the SDK, you'll need to have an initialized MeterProvider that will let you create a go.opentelemetry.io/otel/metric.Meter.

Here's how you might initialize a metrics provider.

package main

import (
	"context"
	"log"

	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/resource"

	semconv "go.opentelemetry.io/otel/semconv/v1.24.0"
)

func main() {
	// Create resource.
	res, err := resource.Merge(resource.Default(),
		resource.NewWithAttributes(semconv.SchemaURL,
			semconv.ServiceName("my-service"),
			semconv.ServiceVersion("0.1.0"),
		))
	if err != nil {
		log.Fatalln(err)
	}

	// This reader is used as a stand-in for a reader that will actually export
	// data. See https://pkg.go.dev/go.opentelemetry.io/otel/exporters for
	// exporters that can be used as or with readers.
	reader := metric.NewManualReader()

	// Create a meter provider.
	// You can pass this instance directly to your instrumented code if it
	// accepts a MeterProvider instance.
	meterProvider := metric.NewMeterProvider(
		metric.WithResource(res),
		metric.WithReader(reader),
	)

	// Handle shutdown properly so that nothing leaks.
	defer func() {
		err := meterProvider.Shutdown(context.Background())
		if err != nil {
			log.Fatalln(err)
		}
	}()

	// Register as global meter provider so that it can be used via otel.Meter
	// and accessed using otel.GetMeterProvider.
	// Most instrumentation libraries use the global meter provider as default.
	// If the global meter provider is not set then a no-op implementation
	// is used, which fails to generate data.
	otel.SetMeterProvider(meterProvider)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrExporterShutdown = fmt.Errorf("exporter is shutdown")

ErrExporterShutdown is returned if Export or Shutdown are called after an Exporter has been Shutdown.

View Source
var ErrInstrumentName = errors.New("invalid instrument name")

ErrInstrumentName indicates the created instrument has an invalid name. Valid names must consist of 255 or fewer characters including alphanumeric, _, ., -, / and start with a letter.

View Source
var ErrReaderNotRegistered = fmt.Errorf("reader is not registered")

ErrReaderNotRegistered is returned if Collect or Shutdown are called before the reader is registered with a MeterProvider.

View Source
var ErrReaderShutdown = fmt.Errorf("reader is shutdown")

ErrReaderShutdown is returned if Collect or Shutdown are called after a reader has been Shutdown once.

Functions

func DefaultTemporalitySelector added in v0.32.0

func DefaultTemporalitySelector(InstrumentKind) metricdata.Temporality

DefaultTemporalitySelector is the default TemporalitySelector used if WithTemporalitySelector is not provided. CumulativeTemporality will be used for all instrument kinds if this TemporalitySelector is used.

Types

type Aggregation added in v0.40.0

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

Aggregation is the aggregation used to summarize recorded measurements.

func DefaultAggregationSelector added in v0.32.0

func DefaultAggregationSelector(ik InstrumentKind) Aggregation

DefaultAggregationSelector returns the default aggregation and parameters that will be used to summarize measurement made from an instrument of InstrumentKind. This AggregationSelector using the following selection mapping: Counter ⇨ Sum, Observable Counter ⇨ Sum, UpDownCounter ⇨ Sum, Observable UpDownCounter ⇨ Sum, Observable Gauge ⇨ LastValue, Histogram ⇨ ExplicitBucketHistogram.

type AggregationBase2ExponentialHistogram added in v0.40.0

type AggregationBase2ExponentialHistogram struct {
	// MaxSize is the maximum number of buckets to use for the histogram.
	MaxSize int32
	// MaxScale is the maximum resolution scale to use for the histogram.
	//
	// MaxScale has a maximum value of 20. Using a value of 20 means the
	// maximum number of buckets that can fit within the range of a
	// signed 32-bit integer index could be used.
	//
	// MaxScale has a minimum value of -10. Using a value of -10 means only
	// two buckets will be used.
	MaxScale int32

	// NoMinMax indicates whether to not record the min and max of the
	// distribution. By default, these extrema are recorded.
	//
	// Recording these extrema for cumulative data is expected to have little
	// value, they will represent the entire life of the instrument instead of
	// just the current collection cycle. It is recommended to set this to true
	// for that type of data to avoid computing the low-value extrema.
	NoMinMax bool
}

AggregationBase2ExponentialHistogram is an Aggregation that summarizes a set of measurements as an histogram with bucket widths that grow exponentially.

type AggregationDefault added in v0.40.0

type AggregationDefault struct{} // AggregationDefault has no parameters.

AggregationDefault is an Aggregation that uses the default instrument kind selection mapping to select another Aggregation. A metric reader can be configured to make an aggregation selection based on instrument kind that differs from the default. This Aggregation ensures the default is used.

See the DefaultAggregationSelector for information about the default instrument kind selection mapping.

type AggregationDrop added in v0.40.0

type AggregationDrop struct{} // AggregationDrop has no parameters.

AggregationDrop is an Aggregation that drops all recorded data.

type AggregationExplicitBucketHistogram added in v0.40.0

type AggregationExplicitBucketHistogram struct {
	// Boundaries are the increasing bucket boundary values. Boundary values
	// define bucket upper bounds. Buckets are exclusive of their lower
	// boundary and inclusive of their upper bound (except at positive
	// infinity). A measurement is defined to fall into the greatest-numbered
	// bucket with a boundary that is greater than or equal to the
	// measurement. As an example, boundaries defined as:
	//
	// []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 1000}
	//
	// Will define these buckets:
	//
	// (-∞, 0], (0, 5.0], (5.0, 10.0], (10.0, 25.0], (25.0, 50.0],
	// (50.0, 75.0], (75.0, 100.0], (100.0, 250.0], (250.0, 500.0],
	// (500.0, 1000.0], (1000.0, +∞)
	Boundaries []float64
	// NoMinMax indicates whether to not record the min and max of the
	// distribution. By default, these extrema are recorded.
	//
	// Recording these extrema for cumulative data is expected to have little
	// value, they will represent the entire life of the instrument instead of
	// just the current collection cycle. It is recommended to set this to true
	// for that type of data to avoid computing the low-value extrema.
	NoMinMax bool
}

AggregationExplicitBucketHistogram is an Aggregation that summarizes a set of measurements as an histogram with explicitly defined buckets.

type AggregationLastValue added in v0.40.0

type AggregationLastValue struct{} // AggregationLastValue has no parameters.

AggregationLastValue is an Aggregation that summarizes a set of measurements as the last one made.

type AggregationSelector added in v0.32.0

type AggregationSelector func(InstrumentKind) Aggregation

AggregationSelector selects the aggregation and the parameters to use for that aggregation based on the InstrumentKind.

If the Aggregation returned is nil or DefaultAggregation, the selection from DefaultAggregationSelector will be used.

type AggregationSum added in v0.40.0

type AggregationSum struct{} // AggregationSum has no parameters.

AggregationSum is an Aggregation that summarizes a set of measurements as their arithmetic sum.

type Exporter added in v0.32.0

type Exporter interface {
	// Temporality returns the Temporality to use for an instrument kind.
	//
	// This method needs to be concurrent safe with itself and all the other
	// Exporter methods.
	Temporality(InstrumentKind) metricdata.Temporality

	// Aggregation returns the Aggregation to use for an instrument kind.
	//
	// This method needs to be concurrent safe with itself and all the other
	// Exporter methods.
	Aggregation(InstrumentKind) Aggregation

	// Export serializes and transmits metric data to a receiver.
	//
	// This is called synchronously, there is no concurrency safety
	// requirement. Because of this, it is critical that all timeouts and
	// cancellations of the passed context be honored.
	//
	// All retry logic must be contained in this function. The SDK does not
	// implement any retry logic. All errors returned by this function are
	// considered unrecoverable and will be reported to a configured error
	// Handler.
	//
	// The passed ResourceMetrics may be reused when the call completes. If an
	// exporter needs to hold this data after it returns, it needs to make a
	// copy.
	Export(context.Context, *metricdata.ResourceMetrics) error

	// ForceFlush flushes any metric data held by an exporter.
	//
	// The deadline or cancellation of the passed context must be honored. An
	// appropriate error should be returned in these situations.
	//
	// This method needs to be concurrent safe.
	ForceFlush(context.Context) error

	// Shutdown flushes all metric data held by an exporter and releases any
	// held computational resources.
	//
	// The deadline or cancellation of the passed context must be honored. An
	// appropriate error should be returned in these situations.
	//
	// After Shutdown is called, calls to Export will perform no operation and
	// instead will return an error indicating the shutdown state.
	//
	// This method needs to be concurrent safe.
	Shutdown(context.Context) error
}

Exporter handles the delivery of metric data to external receivers. This is the final component in the metric push pipeline.

type Instrument added in v0.34.0

type Instrument struct {
	// Name is the human-readable identifier of the instrument.
	Name string
	// Description describes the purpose of the instrument.
	Description string
	// Kind defines the functional group of the instrument.
	Kind InstrumentKind
	// Unit is the unit of measurement recorded by the instrument.
	Unit string
	// Scope identifies the instrumentation that created the instrument.
	Scope instrumentation.Scope
	// contains filtered or unexported fields
}

Instrument describes properties an instrument is created with.

type InstrumentKind added in v0.34.0

type InstrumentKind uint8

InstrumentKind is the identifier of a group of instruments that all performing the same function.

const (

	// InstrumentKindCounter identifies a group of instruments that record
	// increasing values synchronously with the code path they are measuring.
	InstrumentKindCounter InstrumentKind
	// InstrumentKindUpDownCounter identifies a group of instruments that
	// record increasing and decreasing values synchronously with the code path
	// they are measuring.
	InstrumentKindUpDownCounter
	// InstrumentKindHistogram identifies a group of instruments that record a
	// distribution of values synchronously with the code path they are
	// measuring.
	InstrumentKindHistogram
	// InstrumentKindObservableCounter identifies a group of instruments that
	// record increasing values in an asynchronous callback.
	InstrumentKindObservableCounter
	// InstrumentKindObservableUpDownCounter identifies a group of instruments
	// that record increasing and decreasing values in an asynchronous
	// callback.
	InstrumentKindObservableUpDownCounter
	// InstrumentKindObservableGauge identifies a group of instruments that
	// record current values in an asynchronous callback.
	InstrumentKindObservableGauge
)

func (InstrumentKind) String added in v0.40.0

func (i InstrumentKind) String() string

type ManualReader added in v0.40.0

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

ManualReader is a simple Reader that allows an application to read metrics on demand.

func NewManualReader added in v0.32.0

func NewManualReader(opts ...ManualReaderOption) *ManualReader

NewManualReader returns a Reader which is directly called to collect metrics.

func (*ManualReader) Collect added in v0.40.0

Collect gathers all metric data related to the Reader from the SDK and other Producers and stores the result in rm.

Collect will return an error if called after shutdown. Collect will return an error if rm is a nil ResourceMetrics. Collect will return an error if the context's Done channel is closed.

This method is safe to call concurrently.

func (*ManualReader) MarshalLog added in v0.40.0

func (r *ManualReader) MarshalLog() interface{}

MarshalLog returns logging data about the ManualReader.

func (*ManualReader) Shutdown added in v0.40.0

func (mr *ManualReader) Shutdown(context.Context) error

Shutdown closes any connections and frees any resources used by the reader.

This method is safe to call concurrently.

type ManualReaderOption added in v0.32.0

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

ManualReaderOption applies a configuration option value to a ManualReader.

func WithAggregationSelector added in v0.32.0

func WithAggregationSelector(selector AggregationSelector) ManualReaderOption

WithAggregationSelector sets the AggregationSelector a reader will use to determine the aggregation to use for an instrument based on its kind. If this option is not used, the reader will use the DefaultAggregationSelector or the aggregation explicitly passed for a view matching an instrument.

func WithTemporalitySelector added in v0.32.0

func WithTemporalitySelector(selector TemporalitySelector) ManualReaderOption

WithTemporalitySelector sets the TemporalitySelector a reader will use to determine the Temporality of an instrument based on its kind. If this option is not used, the reader will use the DefaultTemporalitySelector.

type MeterProvider added in v0.32.0

type MeterProvider struct {
	embedded.MeterProvider
	// contains filtered or unexported fields
}

MeterProvider handles the creation and coordination of Meters. All Meters created by a MeterProvider will be associated with the same Resource, have the same Views applied to them, and have their produced metric telemetry passed to the configured Readers.

func NewMeterProvider added in v0.32.0

func NewMeterProvider(options ...Option) *MeterProvider

NewMeterProvider returns a new and configured MeterProvider.

By default, the returned MeterProvider is configured with the default Resource and no Readers. Readers cannot be added after a MeterProvider is created. This means the returned MeterProvider, one created with no Readers, will perform no operations.

func (*MeterProvider) ForceFlush added in v0.32.0

func (mp *MeterProvider) ForceFlush(ctx context.Context) error

ForceFlush flushes all pending telemetry.

This method honors the deadline or cancellation of ctx. An appropriate error will be returned in these situations. There is no guaranteed that all telemetry be flushed or all resources have been released in these situations.

ForceFlush calls ForceFlush(context.Context) error on all Readers that implements this method.

This method is safe to call concurrently.

func (*MeterProvider) Meter added in v0.32.0

func (mp *MeterProvider) Meter(name string, options ...metric.MeterOption) metric.Meter

Meter returns a Meter with the given name and configured with options.

The name should be the name of the instrumentation scope creating telemetry. This name may be the same as the instrumented code only if that code provides built-in instrumentation.

Calls to the Meter method after Shutdown has been called will return Meters that perform no operations.

This method is safe to call concurrently.

func (*MeterProvider) Shutdown added in v0.32.0

func (mp *MeterProvider) Shutdown(ctx context.Context) error

Shutdown shuts down the MeterProvider flushing all pending telemetry and releasing any held computational resources.

This call is idempotent. The first call will perform all flush and releasing operations. Subsequent calls will perform no action and will return an error stating this.

Measurements made by instruments from meters this MeterProvider created will not be exported after Shutdown is called.

This method honors the deadline or cancellation of ctx. An appropriate error will be returned in these situations. There is no guaranteed that all telemetry be flushed or all resources have been released in these situations.

This method is safe to call concurrently.

type Option added in v0.32.0

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

Option applies a configuration option value to a MeterProvider.

func WithReader added in v0.32.0

func WithReader(r Reader) Option

WithReader associates Reader r with a MeterProvider.

By default, if this option is not used, the MeterProvider will perform no operations; no data will be exported without a Reader.

func WithResource added in v0.32.0

func WithResource(res *resource.Resource) Option

WithResource associates a Resource with a MeterProvider. This Resource represents the entity producing telemetry and is associated with all Meters the MeterProvider will create.

By default, if this Option is not used, the default Resource from the go.opentelemetry.io/otel/sdk/resource package will be used.

func WithView added in v0.34.0

func WithView(views ...View) Option

WithView associates views a MeterProvider.

Views are appended to existing ones in a MeterProvider if this option is used multiple times.

By default, if this option is not used, the MeterProvider will use the default view.

type PeriodicReader added in v0.40.0

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

PeriodicReader is a Reader that continuously collects and exports metric data at a set interval.

func NewPeriodicReader added in v0.32.0

func NewPeriodicReader(exporter Exporter, options ...PeriodicReaderOption) *PeriodicReader

NewPeriodicReader returns a Reader that collects and exports metric data to the exporter at a defined interval. By default, the returned Reader will collect and export data every 60 seconds, and will cancel any attempts that exceed 30 seconds, collect and export combined. The collect and export time are not counted towards the interval between attempts.

The Collect method of the returned Reader continues to gather and return metric data to the user. It will not automatically send that data to the exporter. That is left to the user to accomplish.

func (*PeriodicReader) Collect added in v0.40.0

Collect gathers all metric data related to the Reader from the SDK and other Producers and stores the result in rm. The metric data is not exported to the configured exporter, it is left to the caller to handle that if desired.

Collect will return an error if called after shutdown. Collect will return an error if rm is a nil ResourceMetrics. Collect will return an error if the context's Done channel is closed.

This method is safe to call concurrently.

func (*PeriodicReader) ForceFlush added in v0.40.0

func (r *PeriodicReader) ForceFlush(ctx context.Context) error

ForceFlush flushes pending telemetry.

This method is safe to call concurrently.

func (*PeriodicReader) MarshalLog added in v0.40.0

func (r *PeriodicReader) MarshalLog() interface{}

MarshalLog returns logging data about the PeriodicReader.

func (*PeriodicReader) Shutdown added in v0.40.0

func (r *PeriodicReader) Shutdown(ctx context.Context) error

Shutdown flushes pending telemetry and then stops the export pipeline.

This method is safe to call concurrently.

type PeriodicReaderOption added in v0.32.0

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

PeriodicReaderOption applies a configuration option value to a PeriodicReader.

func WithInterval added in v0.32.0

func WithInterval(d time.Duration) PeriodicReaderOption

WithInterval configures the intervening time between exports for a PeriodicReader.

This option overrides any value set for the OTEL_METRIC_EXPORT_INTERVAL environment variable.

If this option is not used or d is less than or equal to zero, 60 seconds is used as the default.

func WithTimeout added in v0.32.0

func WithTimeout(d time.Duration) PeriodicReaderOption

WithTimeout configures the time a PeriodicReader waits for an export to complete before canceling it. This includes an export which occurs as part of Shutdown or ForceFlush if the user passed context does not have a deadline. If the user passed context does have a deadline, it will be used instead.

This option overrides any value set for the OTEL_METRIC_EXPORT_TIMEOUT environment variable.

If this option is not used or d is less than or equal to zero, 30 seconds is used as the default.

type Producer added in v0.35.0

type Producer interface {

	// Produce returns aggregated metrics from an external source.
	//
	// This method should be safe to call concurrently.
	Produce(context.Context) ([]metricdata.ScopeMetrics, error)
}

Producer produces metrics for a Reader from an external source.

type Reader added in v0.32.0

type Reader interface {

	// Collect gathers and returns all metric data related to the Reader from
	// the SDK and stores it in out. An error is returned if this is called
	// after Shutdown or if out is nil.
	//
	// This method needs to be concurrent safe, and the cancellation of the
	// passed context is expected to be honored.
	Collect(ctx context.Context, rm *metricdata.ResourceMetrics) error

	// Shutdown flushes all metric measurements held in an export pipeline and releases any
	// held computational resources.
	//
	// This deadline or cancellation of the passed context are honored. An appropriate
	// error will be returned in these situations. There is no guaranteed that all
	// telemetry be flushed or all resources have been released in these
	// situations.
	//
	// After Shutdown is called, calls to Collect will perform no operation and instead will return
	// an error indicating the shutdown state.
	//
	// This method needs to be concurrent safe.
	Shutdown(context.Context) error
	// contains filtered or unexported methods
}

Reader is the interface used between the SDK and an exporter. Control flow is bi-directional through the Reader, since the SDK initiates ForceFlush and Shutdown while the exporter initiates collection. The Register() method here informs the Reader that it can begin reading, signaling the start of bi-directional control flow.

Typically, push-based exporters that are periodic will implement PeroidicExporter themselves and construct a PeriodicReader to satisfy this interface.

Pull-based exporters will typically implement Register themselves, since they read on demand.

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

type ReaderOption added in v0.32.0

type ReaderOption interface {
	PeriodicReaderOption
	ManualReaderOption
}

ReaderOption is an option which can be applied to manual or Periodic readers.

func WithProducer added in v0.40.0

func WithProducer(p Producer) ReaderOption

WithProducers registers producers as an external Producer of metric data for this Reader.

type Stream added in v0.34.0

type Stream struct {
	// Name is the human-readable identifier of the stream.
	Name string
	// Description describes the purpose of the data.
	Description string
	// Unit is the unit of measurement recorded.
	Unit string
	// Aggregation the stream uses for an instrument.
	Aggregation Aggregation
	// AttributeFilter is an attribute Filter applied to the attributes
	// recorded for an instrument's measurement. If the filter returns false
	// the attribute will not be recorded, otherwise, if it returns true, it
	// will record the attribute.
	//
	// Use NewAllowKeysFilter from "go.opentelemetry.io/otel/attribute" to
	// provide an allow-list of attribute keys here.
	AttributeFilter attribute.Filter
}

Stream describes the stream of data an instrument produces.

type TemporalitySelector added in v0.32.0

type TemporalitySelector func(InstrumentKind) metricdata.Temporality

TemporalitySelector selects the temporality to use based on the InstrumentKind.

type View added in v0.34.0

type View func(Instrument) (Stream, bool)

View is an override to the default behavior of the SDK. It defines how data should be collected for certain instruments. It returns true and the exact Stream to use for matching Instruments. Otherwise, if the view does not match, false is returned.

Example
package main

import (
	"fmt"
	"regexp"

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

func main() {
	// The NewView function provides convenient creation of common Views
	// construction. However, it is limited in what it can create.
	//
	// When NewView is not able to provide the functionally needed, a custom
	// View can be constructed directly. Here a custom View is constructed that
	// uses Go's regular expression matching to ensure all data stream names
	// have a suffix of the units it uses.

	re := regexp.MustCompile(`[._](ms|byte)$`)
	var view metric.View = func(i metric.Instrument) (metric.Stream, bool) {
		// In a custom View function, you need to explicitly copy
		// the name, description, and unit.
		s := metric.Stream{Name: i.Name, Description: i.Description, Unit: i.Unit}
		// Any instrument that does not have a unit suffix defined, but has a
		// dimensional unit defined, update the name with a unit suffix.
		if re.MatchString(i.Name) {
			return s, false
		}
		switch i.Unit {
		case "ms":
			s.Name += ".ms"
		case "By":
			s.Name += ".byte"
		default:
			return s, false
		}
		return s, true
	}

	// The created view can then be registered with the OpenTelemetry metric
	// SDK using the WithView option.
	_ = metric.NewMeterProvider(
		metric.WithView(view),
	)

	// Below is an example of how the view will
	// function in the SDK for certain instruments.
	stream, _ := view(metric.Instrument{
		Name: "computation.time.ms",
		Unit: "ms",
	})
	fmt.Println("name:", stream.Name)

	stream, _ = view(metric.Instrument{
		Name: "heap.size",
		Unit: "By",
	})
	fmt.Println("name:", stream.Name)
}
Output:

name: computation.time.ms
name: heap.size.byte

func NewView added in v0.34.0

func NewView(criteria Instrument, mask Stream) View

NewView returns a View that applies the Stream mask for all instruments that match criteria. The returned View will only apply mask if all non-zero-value fields of criteria match the corresponding Instrument passed to the view. If no criteria are provided, all field of criteria are their zero-values, a view that matches no instruments is returned. If you need to match a zero-value field, create a View directly.

The Name field of criteria supports wildcard pattern matching. The "*" wildcard is recognized as matching zero or more characters, and "?" is recognized as matching exactly one character. For example, a pattern of "*" matches all instrument names.

The Stream mask only applies updates for non-zero-value fields. By default, the Instrument the View matches against will be use for the Name, Description, and Unit of the returned Stream and no Aggregation or AttributeFilter are set. All non-zero-value fields of mask are used instead of the default. If you need to zero out an Stream field returned from a View, create a View directly.

Example
package main

import (
	"fmt"

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

func main() {
	// Create a view that renames the "latency" instrument from the v0.34.0
	// version of the "http" instrumentation library as "request.latency".
	view := metric.NewView(metric.Instrument{
		Name: "latency",
		Scope: instrumentation.Scope{
			Name:    "http",
			Version: "0.34.0",
		},
	}, metric.Stream{Name: "request.latency"})

	// The created view can then be registered with the OpenTelemetry metric
	// SDK using the WithView option.
	_ = metric.NewMeterProvider(
		metric.WithView(view),
	)

	// Below is an example of how the view will
	// function in the SDK for certain instruments.
	stream, _ := view(metric.Instrument{
		Name:        "latency",
		Description: "request latency",
		Unit:        "ms",
		Kind:        metric.InstrumentKindCounter,
		Scope: instrumentation.Scope{
			Name:      "http",
			Version:   "0.34.0",
			SchemaURL: "https://opentelemetry.io/schemas/1.0.0",
		},
	})
	fmt.Println("name:", stream.Name)
	fmt.Println("description:", stream.Description)
	fmt.Println("unit:", stream.Unit)
}
Output:

name: request.latency
description: request latency
unit: ms
Example (AttributeFilter)
package main

import (
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/sdk/instrumentation"
	"go.opentelemetry.io/otel/sdk/metric"
)

func main() {
	// Create a view that removes the "http.request.method" attribute recorded
	// by the "latency" instrument from the "http" instrumentation library.
	view := metric.NewView(
		metric.Instrument{
			Name:  "latency",
			Scope: instrumentation.Scope{Name: "http"},
		},
		metric.Stream{AttributeFilter: attribute.NewDenyKeysFilter("http.request.method")},
	)

	// The created view can then be registered with the OpenTelemetry metric
	// SDK using the WithView option.
	_ = metric.NewMeterProvider(
		metric.WithView(view),
	)
}
Output:

Example (Drop)
package main

import (
	"go.opentelemetry.io/otel/sdk/instrumentation"
	"go.opentelemetry.io/otel/sdk/metric"
)

func main() {
	// Create a view that drops the "latency" instrument from the "http"
	// instrumentation library.
	view := metric.NewView(
		metric.Instrument{
			Name:  "latency",
			Scope: instrumentation.Scope{Name: "http"},
		},
		metric.Stream{Aggregation: metric.AggregationDrop{}},
	)

	// The created view can then be registered with the OpenTelemetry metric
	// SDK using the WithView option.
	_ = metric.NewMeterProvider(
		metric.WithView(view),
	)
}
Output:

Example (ExponentialHistogram)
package main

import (
	"go.opentelemetry.io/otel/sdk/instrumentation"
	"go.opentelemetry.io/otel/sdk/metric"
)

func main() {
	// Create a view that makes the "latency" instrument from the "http"
	// instrumentation library to be reported as an exponential histogram.
	view := metric.NewView(
		metric.Instrument{
			Name:  "latency",
			Scope: instrumentation.Scope{Name: "http"},
		},
		metric.Stream{
			Aggregation: metric.AggregationBase2ExponentialHistogram{
				MaxSize:  160,
				MaxScale: 20,
			},
		},
	)

	// The created view can then be registered with the OpenTelemetry metric
	// SDK using the WithView option.
	_ = metric.NewMeterProvider(
		metric.WithView(view),
	)
}
Output:

Example (Wildcard)
package main

import (
	"fmt"

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

func main() {
	// Create a view that sets unit to milliseconds for any instrument with a
	// name suffix of ".ms".
	view := metric.NewView(
		metric.Instrument{Name: "*.ms"},
		metric.Stream{Unit: "ms"},
	)

	// The created view can then be registered with the OpenTelemetry metric
	// SDK using the WithView option.
	_ = metric.NewMeterProvider(
		metric.WithView(view),
	)

	// Below is an example of how the view will
	// function in the SDK for certain instruments.
	stream, _ := view(metric.Instrument{
		Name: "computation.time.ms",
		Unit: "1",
	})
	fmt.Println("name:", stream.Name)
	fmt.Println("unit:", stream.Unit)
}
Output:

name: computation.time.ms
unit: ms

Directories

Path Synopsis
aggregate
Package aggregate provides aggregate types used compute aggregations and cycle the state of metric measurements made by the SDK.
Package aggregate provides aggregate types used compute aggregations and cycle the state of metric measurements made by the SDK.
exemplar
Package exemplar provides an implementation of the OpenTelemetry exemplar reservoir to be used in metric collection pipelines.
Package exemplar provides an implementation of the OpenTelemetry exemplar reservoir to be used in metric collection pipelines.
x
Package x contains support for OTel metric SDK experimental features.
Package x contains support for OTel metric SDK experimental features.
metricdatatest
Package metricdatatest provides testing functionality for use with the metricdata package.
Package metricdatatest provides testing functionality for use with the metricdata package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL