metric
v1.47.0
Documentation
pkg.go.dev ↗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.
Note that attributes filtered out by a View may still appear on Exemplars, because Exemplars are recorded with the dropped measurement attributes when View attribute filtering is applied.
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.
To avoid leaking memory, the SDK returns the same instrument for calls to create new instruments with the same Name, Unit, and Description. Importantly, callbacks provided using metric.WithFloat64Callback or metric.WithInt64Callback will only apply for the first instrument created with a given Name, Unit, and Description. Instead, use Meter.RegisterCallback and Registration.Unregister to add and remove callbacks without leaking memory.
Cardinality Limits
Cardinality refers to the number of unique attributes collected. High cardinality can lead to excessive memory usage, increased storage costs, and backend performance issues.
By default, the OpenTelemetry Go Metric SDK enforces a cardinality limit of 2000.
New attribute sets are dropped when the cardinality limit is reached. The measurement of these sets are aggregated into a special attribute set containing attribute.Bool("otel.metric.overflow", true). This ensures total metric values (e.g., Sum, Count) remain correct for the collection cycle, but information about the specific dropped sets is not preserved.
Recommendations:
- Tune the limit based on the theoretical maximum combinations or expected active combinations. The SDK default is 2000.
- A too high of a limit increases worst-case memory overhead in the SDK and may cause downstream issues for databases that cannot handle high cardinality.
- A too low of a limit causes loss of attribute detail as more data falls into overflow.
Ordering and Collection Guarantees
For performance reasons, the SDK does not guarantee that the order in which synchronous measurements are made to the SDK is reflected in the collected metric data. This means that even when a single goroutine makes sequential synchronous measurements, it is possible for a later measurement to be included in the collected metric data when an earlier measurement is not. This applies to measurements made to different instruments, or to different attribute sets on the same instrument. Sequential measurements made to the same instrument and with the same attributes are guaranteed to preserve ordering with respect to collection.
Additionally, the SDK does not guarantee that exemplars are always included in the same batch of metric data as the measurement they are associated with.
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](#MeterProvider) that will let you create a [go.opentelemetry.io/otel/metric.Meter](/go.opentelemetry.io/otel/metric#Meter). Here's how you might initialize a metrics provider.{
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)
}
reader := metric.NewManualReader()
meterProvider := metric.NewMeterProvider(
metric.WithResource(res),
metric.WithReader(reader),
)
defer func() {
err := meterProvider.Shutdown(context.Background())
if err != nil {
log.Fatalln(err)
}
}()
otel.SetMeterProvider(meterProvider)
}
Variables
ErrExporterShutdown
var ErrExporterShutdown = errors.New("exporter is shutdown")
ErrExporterShutdown is returned if Export or Shutdown are called after an Exporter has been Shutdown.
ErrInstrumentName
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.
ErrReaderNotRegistered
var ErrReaderNotRegistered = errors.New("reader is not registered")
ErrReaderNotRegistered is returned if Collect or Shutdown are called before the reader is registered with a MeterProvider.
ErrReaderShutdown
var ErrReaderShutdown = errors.New("reader is shutdown")
ErrReaderShutdown is returned if Collect or Shutdown are called after a reader has been Shutdown once.
Functions
CumulativeTemporalitySelector
func CumulativeTemporalitySelector(InstrumentKind) metricdata.Temporality
CumulativeTemporalitySelector is the TemporalitySelector that uses a cumulative temporality for all instrument kinds.
DefaultExemplarReservoirProviderSelector
func DefaultExemplarReservoirProviderSelector(agg Aggregation) exemplar.ReservoirProvider
DefaultExemplarReservoirProviderSelector returns the default exemplar.ReservoirProvider for the provided Aggregation.
For explicit bucket histograms with more than 1 bucket, it uses the exemplar.HistogramReservoirProvider. For exponential histograms, it uses the exemplar.FixedSizeReservoirProvider with a size of min(20, max_buckets). For all other aggregations, it uses the exemplar.FixedSizeReservoirProvider with a size equal to the number of CPUs.
Exemplar default reservoirs MAY change in a minor version bump. No guarantees are made on the shape or statistical properties of returned exemplars.
DefaultTemporalitySelector
func DefaultTemporalitySelector(k 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.
DeltaTemporalitySelector
func DeltaTemporalitySelector(k InstrumentKind) metricdata.Temporality
DeltaTemporalitySelector is the TemporalitySelector that uses a delta temporality for instrument kinds: counter, histogram, observable counter All other instruments use cumulative temporality.
LowMemoryTemporalitySelector
func LowMemoryTemporalitySelector(k InstrumentKind) metricdata.Temporality
LowMemoryTemporalitySelector is the TemporalitySelector that uses delta temporality for counters and histograms. All other instruments use cumulative temporality.
Types
Aggregation
type Aggregation interface {
// contains filtered or unexported methods
}
Aggregation is the aggregation used to summarize recorded measurements.
DefaultAggregationSelector
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.
The default ExplicitBucketHistogram boundaries are designed for millisecond-scale latency values. Boundaries are interpreted relative to the values recorded for the instrument and are not rescaled when an instrument is created with a different unit (e.g. via go.opentelemetry.io/otel/metric.WithUnit). Instrumentation authors should supply appropriate boundaries per instrument via go.opentelemetry.io/otel/metric.WithExplicitBucketBoundaries; end users can also override boundaries for a specific instrument with a View.
AggregationBase2ExponentialHistogram
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 a histogram with bucket widths that grow exponentially.
AggregationDefault
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.
AggregationDrop
type AggregationDrop struct{} // AggregationDrop has no parameters.
AggregationDrop is an Aggregation that drops all recorded data.
AggregationExplicitBucketHistogram
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 a histogram with explicitly defined buckets.
AggregationLastValue
type AggregationLastValue struct{} // AggregationLastValue has no parameters.
AggregationLastValue is an Aggregation that summarizes a set of measurements as the last one made.
AggregationSelector
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.
AggregationSum
type AggregationSum struct{} // AggregationSum has no parameters.
AggregationSum is an Aggregation that summarizes a set of measurements as their arithmetic sum.
CardinalityLimitSelector
type CardinalityLimitSelector func(InstrumentKind) (limit int, fallback bool)
CardinalityLimitSelector selects the cardinality limit to use based on the InstrumentKind. The cardinality limit is the maximum number of distinct attribute sets that can be recorded for a single instrument.
The selector returns (limit, fallback). When fallback is true, the pipeline falls back to the provider's global cardinality limit. When fallback is false, the limit is applied: a value of 0 or less means no limit, and a positive value is the limit for that kind. To avoid overriding the provider's global limit, return (0, true).
ExemplarReservoirProviderSelector
type ExemplarReservoirProviderSelector func(Aggregation) exemplar.ReservoirProvider
ExemplarReservoirProviderSelector selects the exemplar.ReservoirProvider to use based on the Aggregation of the metric.
Exporter
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.
Instrument
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.
Instrument.IsEmpty
func (i Instrument) IsEmpty() bool
IsEmpty reports whether all Instrument fields are their zero-value.
InstrumentKind
type InstrumentKind uint8
InstrumentKind is the identifier of a group of instruments that all performing the same function.
InstrumentKindCounter (7 declarations)
const ( // InstrumentKindCounter identifies a group of instruments that record // increasing values synchronously with the code path they are measuring. InstrumentKindCounter InstrumentKind = 1 // InstrumentKindUpDownCounter identifies a group of instruments that // record increasing and decreasing values synchronously with the code path // they are measuring. InstrumentKindUpDownCounter InstrumentKind = 2 // InstrumentKindHistogram identifies a group of instruments that record a // distribution of values synchronously with the code path they are // measuring. InstrumentKindHistogram InstrumentKind = 3 // InstrumentKindObservableCounter identifies a group of instruments that // record increasing values in an asynchronous callback. InstrumentKindObservableCounter InstrumentKind = 4 // InstrumentKindObservableUpDownCounter identifies a group of instruments // that record increasing and decreasing values in an asynchronous // callback. InstrumentKindObservableUpDownCounter InstrumentKind = 5 // InstrumentKindObservableGauge identifies a group of instruments that // record current values in an asynchronous callback. InstrumentKindObservableGauge InstrumentKind = 6 // InstrumentKindGauge identifies a group of instruments that record // instantaneous values synchronously with the code path they are // measuring. InstrumentKindGauge InstrumentKind = 7 )
InstrumentKind.String
func (i InstrumentKind) String() string
ManualReader
type ManualReader struct {
// contains filtered or unexported fields
}
ManualReader is a simple Reader that allows an application to read metrics on demand.
NewManualReader
func NewManualReader(opts ...ManualReaderOption) *ManualReader
NewManualReader returns a Reader which is directly called to collect metrics.
ManualReader.Collect
func (mr *ManualReader) Collect(ctx context.Context, rm *metricdata.ResourceMetrics) error
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.
ManualReader.MarshalLog
func (mr *ManualReader) MarshalLog() any
MarshalLog returns logging data about the ManualReader.
ManualReader.Shutdown
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.
ManualReaderOption
type ManualReaderOption interface {
// contains filtered or unexported methods
}
ManualReaderOption applies a configuration option value to a ManualReader.
WithAggregationSelector
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.
WithTemporalitySelector
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.
MeterProvider
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.
NewMeterProvider
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.
MeterProvider.ForceFlush
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.
MeterProvider.Meter
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.
MeterProvider.Shutdown
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.
Option
type Option interface {
// contains filtered or unexported methods
}
Option applies a configuration option value to a MeterProvider.
WithCardinalityLimit
func WithCardinalityLimit(limit int) Option
WithCardinalityLimit sets the global cardinality limit for the MeterProvider.
The cardinality limit is the hard limit on the number of metric datapoints that can be collected for a single instrument in a single collect cycle.
By default, if this option is not used, a limit of 2000 is applied.
Setting this to a zero or negative means no limit is applied. This value applies to all instrument kinds, but can be overridden per kind by the reader's cardinality limit selector (see WithCardinalityLimitSelector).
WithExemplarFilter
func WithExemplarFilter(filter exemplar.Filter) Option
WithExemplarFilter configures the exemplar filter.
The exemplar filter determines which measurements are offered to the exemplar reservoir, but the exemplar reservoir makes the final decision of whether to store an exemplar.
The filter must not be nil.
By default, the exemplar.TraceBasedFilter is used. Exemplars can be entirely disabled by providing the exemplar.AlwaysOffFilter.
Example (custom)
{
customFilter := func(ctx context.Context) bool {
return ctx.Err() != nil
}
_ = metric.NewMeterProvider(
metric.WithExemplarFilter(customFilter),
)
}
Example (disabled)
{
_ = metric.NewMeterProvider(
metric.WithExemplarFilter(exemplar.AlwaysOffFilter),
)
}
WithReader
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.
WithResource
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.
WithView
func WithView(views ...View) Option
WithView associates views with 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.
PeriodicReader
type PeriodicReader struct {
// contains filtered or unexported fields
}
PeriodicReader is a Reader that continuously collects and exports metric data at a set interval.
NewPeriodicReader
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.
PeriodicReader.Collect
func (r *PeriodicReader) Collect(ctx context.Context, rm *metricdata.ResourceMetrics) error
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.
PeriodicReader.ForceFlush
func (r *PeriodicReader) ForceFlush(ctx context.Context) error
ForceFlush flushes pending telemetry.
This method is safe to call concurrently.
PeriodicReader.MarshalLog
func (r *PeriodicReader) MarshalLog() any
MarshalLog returns logging data about the PeriodicReader.
PeriodicReader.Shutdown
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.
PeriodicReaderOption
type PeriodicReaderOption interface {
// contains filtered or unexported methods
}
PeriodicReaderOption applies a configuration option value to a PeriodicReader.
WithInterval
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.
WithMaxExportBatchSize
func WithMaxExportBatchSize(size int) PeriodicReaderOption
WithMaxExportBatchSize configures the maximum number of metric data points in a batch that are exported at once.
If this option is not used or size is less than or equal to zero, no limit is applied.
WithTimeout
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.
Producer
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.
Reader
type Reader interface {
// Collect gathers and returns all metric data related to the Reader from
// the SDK and stores it in rm. An error is returned if this is called
// after Shutdown or if rm 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 PeriodicExporter 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.
ReaderOption
type ReaderOption interface {
PeriodicReaderOption
ManualReaderOption
}
ReaderOption is an option which can be applied to manual or Periodic readers.
WithCardinalityLimitSelector
func WithCardinalityLimitSelector(selector CardinalityLimitSelector) ReaderOption
WithCardinalityLimitSelector sets the CardinalityLimitSelector a reader will use to determine the cardinality limit for an instrument based on its kind. If this option is not used, the reader will use the defaultCardinalityLimitSelector.
The selector should return (limit, false) to set a positive limit, (0, false) to explicitly specify unlimited, or (0, true) to fall back to the provider's global limit.
See CardinalityLimitSelector for more details.
WithProducer
func WithProducer(p Producer) ReaderOption
WithProducer registers producers as an external Producer of metric data for this Reader.
Stream
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.
//
// If nil, the instrument's advisory attribute keys are used. If the
// instrument has no advisory attribute keys, all attributes are recorded.
//
// Note that attributes filtered out by a View may still appear on Exemplars,
// because Exemplars are recorded with the dropped measurement attributes
// when View attribute filtering is applied.
//
// Use NewAllowKeysFilter from "go.opentelemetry.io/otel/attribute" to
// provide an allow-list of attribute keys here.
AttributeFilter attribute.Filter
// ExemplarReservoirProvider selects the
// [go.opentelemetry.io/otel/sdk/metric/exemplar.ReservoirProvider] based
// on the [Aggregation].
//
// If unspecified, [DefaultExemplarReservoirProviderSelector] is used.
ExemplarReservoirProviderSelector ExemplarReservoirProviderSelector
}
Stream describes the stream of data an instrument produces.
TemporalitySelector
type TemporalitySelector func(InstrumentKind) metricdata.Temporality
TemporalitySelector selects the temporality to use based on the InstrumentKind.
View
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.
Note that attributes filtered out by a View may still appear on Exemplars, because Exemplars are recorded with the dropped measurement attributes when View attribute filtering is applied.
Example
{
re := regexp.MustCompile(`[._](ms|byte)$`)
var view metric.View = func(i metric.Instrument) (metric.Stream, bool) {
s := metric.Stream{Name: i.Name, Description: i.Description, Unit: i.Unit}
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
}
_ = metric.NewMeterProvider(
metric.WithView(view),
)
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
NewView
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 a Stream field returned from a View, create a View directly.
Example
{
view := metric.NewView(metric.Instrument{
Name: "latency",
Scope: instrumentation.Scope{
Name: "http",
Version: "0.34.0",
},
}, metric.Stream{Name: "request.latency"})
_ = metric.NewMeterProvider(
metric.WithView(view),
)
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.37.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)
{
view := metric.NewView(
metric.Instrument{
Name: "latency",
Scope: instrumentation.Scope{Name: "http"},
},
metric.Stream{AttributeFilter: attribute.NewDenyKeysFilter("http.request.method")},
)
_ = metric.NewMeterProvider(
metric.WithView(view),
)
}
Example (drop)
{
view := metric.NewView(
metric.Instrument{
Name: "latency",
Scope: instrumentation.Scope{Name: "http"},
},
metric.Stream{Aggregation: metric.AggregationDrop{}},
)
_ = metric.NewMeterProvider(
metric.WithView(view),
)
}
Example (exemplarreservoirproviderselector)
{
view := metric.NewView(
metric.Instrument{Name: "*"},
metric.Stream{
ExemplarReservoirProviderSelector: func(agg metric.Aggregation) exemplar.ReservoirProvider {
if _, ok := agg.(metric.AggregationExplicitBucketHistogram); ok {
return exemplar.FixedSizeReservoirProvider(10)
}
return metric.DefaultExemplarReservoirProviderSelector(agg)
},
},
)
_ = metric.NewMeterProvider(
metric.WithView(view),
)
}
Example (exponentialHistogram)
{
view := metric.NewView(
metric.Instrument{
Name: "latency",
Scope: instrumentation.Scope{Name: "http"},
},
metric.Stream{
Aggregation: metric.AggregationBase2ExponentialHistogram{
MaxSize: 160,
MaxScale: 20,
},
},
)
_ = metric.NewMeterProvider(
metric.WithView(view),
)
}
Example (wildcard)
{
view := metric.NewView(
metric.Instrument{Name: "*.ms"},
metric.Stream{Unit: "ms"},
)
_ = metric.NewMeterProvider(
metric.WithView(view),
)
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