1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-08-10 22:31:50 +02:00

Add the golines golangci-lint formatter (#6513)

Ensure consistent line wrapping (<= 120 characters) within the project.
This commit is contained in:
Tyler Yahn
2025-03-30 11:46:44 +01:00
committed by GitHub
parent b59d0591cf
commit 7512a2be2e
96 changed files with 1774 additions and 426 deletions

View File

@@ -47,11 +47,14 @@ func TestLoggerEmit(t *testing.T) {
rWithNoObservedTimestamp := r
rWithNoObservedTimestamp.SetObservedTimestamp(time.Time{})
contextWithSpanContext := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{
TraceID: trace.TraceID{0o1},
SpanID: trace.SpanID{0o2},
TraceFlags: 0x1,
}))
contextWithSpanContext := trace.ContextWithSpanContext(
context.Background(),
trace.NewSpanContext(trace.SpanContextConfig{
TraceID: trace.TraceID{0o1},
SpanID: trace.SpanID{0o2},
TraceFlags: 0x1,
}),
)
testCases := []struct {
name string

View File

@@ -73,6 +73,8 @@ func (f RecordFactory) NewRecord() sdklog.Record {
func set(r *sdklog.Record, name string, value any) {
rVal := reflect.ValueOf(r).Elem()
rf := rVal.FieldByName(name)
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem() // nolint: gosec // conversion of uintptr -> unsafe.Pointer.
rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).
Elem()
// nolint: gosec // conversion of uintptr -> unsafe.Pointer.
rf.Set(reflect.ValueOf(value))
}

View File

@@ -202,9 +202,15 @@ func TestWithResource(t *testing.T) {
want: resource.Default(),
},
{
name: "explicit resource",
options: []LoggerProviderOption{WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)))},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
name: "explicit resource",
options: []LoggerProviderOption{
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
},
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)),
),
},
{
name: "last resource wins",
@@ -212,12 +218,22 @@ func TestWithResource(t *testing.T) {
WithResource(resource.NewSchemaless(attribute.String("rk1", "vk1"), attribute.Int64("rk2", 5))),
WithResource(resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10)),
),
},
{
name: "overlapping attributes with environment resource",
options: []LoggerProviderOption{WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)))},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
name: "overlapping attributes with environment resource",
options: []LoggerProviderOption{
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
},
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)),
),
},
}
for _, tc := range cases {
@@ -296,12 +312,26 @@ func TestLoggerProviderLogger(t *testing.T) {
t.Run("SameLoggers", func(t *testing.T) {
p := NewLoggerProvider()
l0, l1, l2 := p.Logger("l0"), p.Logger("l1"), p.Logger("l0", log.WithInstrumentationAttributes(attribute.String("foo", "bar")))
l0, l1, l2 := p.Logger(
"l0",
), p.Logger(
"l1",
), p.Logger(
"l0",
log.WithInstrumentationAttributes(attribute.String("foo", "bar")),
)
assert.NotSame(t, l0, l1)
assert.NotSame(t, l0, l2)
assert.NotSame(t, l1, l2)
l3, l4, l5 := p.Logger("l0"), p.Logger("l1"), p.Logger("l0", log.WithInstrumentationAttributes(attribute.String("foo", "bar")))
l3, l4, l5 := p.Logger(
"l0",
), p.Logger(
"l1",
), p.Logger(
"l0",
log.WithInstrumentationAttributes(attribute.String("foo", "bar")),
)
assert.Same(t, l0, l3)
assert.Same(t, l1, l4)
assert.Same(t, l2, l5)

View File

@@ -33,7 +33,9 @@ const envVarResourceAttributes = "OTEL_RESOURCE_ATTRIBUTES"
var _ Reader = (*reader)(nil)
func (r *reader) aggregation(kind InstrumentKind) Aggregation { // nolint:revive // import-shadow for method scoped by type.
func (r *reader) aggregation(
kind InstrumentKind,
) Aggregation { // nolint:revive // import-shadow for method scoped by type.
return r.aggregationFunc(kind)
}
@@ -148,9 +150,15 @@ func TestWithResource(t *testing.T) {
want: resource.Default(),
},
{
name: "explicit resource",
options: []Option{WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)))},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
name: "explicit resource",
options: []Option{
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
},
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)),
),
},
{
name: "last resource wins",
@@ -158,12 +166,22 @@ func TestWithResource(t *testing.T) {
WithResource(resource.NewSchemaless(attribute.String("rk1", "vk1"), attribute.Int64("rk2", 5))),
WithResource(resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10)),
),
},
{
name: "overlapping attributes with environment resource",
options: []Option{WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)))},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
name: "overlapping attributes with environment resource",
options: []Option{
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
},
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)),
),
},
}
for _, tc := range cases {

View File

@@ -18,7 +18,10 @@ type ExemplarReservoirProviderSelector func(Aggregation) exemplar.ReservoirProvi
// reservoirFunc returns the appropriately configured exemplar reservoir
// creation func based on the passed InstrumentKind and filter configuration.
func reservoirFunc[N int64 | float64](provider exemplar.ReservoirProvider, filter exemplar.Filter) func(attribute.Set) aggregate.FilteredExemplarReservoir[N] {
func reservoirFunc[N int64 | float64](
provider exemplar.ReservoirProvider,
filter exemplar.Filter,
) func(attribute.Set) aggregate.FilteredExemplarReservoir[N] {
return func(attrs attribute.Set) aggregate.FilteredExemplarReservoir[N] {
return aggregate.NewFilteredExemplarReservoir[N](filter, provider(attrs))
}

View File

@@ -208,7 +208,11 @@ func (i *int64Inst) Enabled(_ context.Context) bool {
return len(i.measures) != 0
}
func (i *int64Inst) aggregate(ctx context.Context, val int64, s attribute.Set) { // nolint:revive // okay to shadow pkg with method.
func (i *int64Inst) aggregate(
ctx context.Context,
val int64,
s attribute.Set,
) { // nolint:revive // okay to shadow pkg with method.
for _, in := range i.measures {
in(ctx, val, s)
}

View File

@@ -121,7 +121,10 @@ func (b Builder[N]) Sum(monotonic bool) (Measure[N], ComputeAggregation) {
// ExplicitBucketHistogram returns a histogram aggregate function input and
// output.
func (b Builder[N]) ExplicitBucketHistogram(boundaries []float64, noMinMax, noSum bool) (Measure[N], ComputeAggregation) {
func (b Builder[N]) ExplicitBucketHistogram(
boundaries []float64,
noMinMax, noSum bool,
) (Measure[N], ComputeAggregation) {
h := newHistogram[N](boundaries, noMinMax, noSum, b.AggregationLimit, b.resFunc())
switch b.Temporality {
case metricdata.DeltaTemporality:
@@ -133,7 +136,10 @@ func (b Builder[N]) ExplicitBucketHistogram(boundaries []float64, noMinMax, noSu
// ExponentialBucketHistogram returns a histogram aggregate function input and
// output.
func (b Builder[N]) ExponentialBucketHistogram(maxSize, maxScale int32, noMinMax, noSum bool) (Measure[N], ComputeAggregation) {
func (b Builder[N]) ExponentialBucketHistogram(
maxSize, maxScale int32,
noMinMax, noSum bool,
) (Measure[N], ComputeAggregation) {
h := newExponentialHistogram[N](maxSize, maxScale, noMinMax, noSum, b.AggregationLimit, b.resFunc())
switch b.Temporality {
case metricdata.DeltaTemporality:

View File

@@ -48,7 +48,12 @@ type expoHistogramDataPoint[N int64 | float64] struct {
zeroCount uint64
}
func newExpoHistogramDataPoint[N int64 | float64](attrs attribute.Set, maxSize int, maxScale int32, noMinMax, noSum bool) *expoHistogramDataPoint[N] { // nolint:revive // we need this control flag
func newExpoHistogramDataPoint[N int64 | float64](
attrs attribute.Set,
maxSize int,
maxScale int32,
noMinMax, noSum bool,
) *expoHistogramDataPoint[N] { // nolint:revive // we need this control flag
f := math.MaxFloat64
ma := N(f) // if N is int64, max will overflow to -9223372036854775808
mi := N(-f)
@@ -283,7 +288,12 @@ func (b *expoBuckets) downscale(delta int32) {
// newExponentialHistogram returns an Aggregator that summarizes a set of
// measurements as an exponential histogram. Each histogram is scoped by attributes
// and the aggregation cycle the measurements were made in.
func newExponentialHistogram[N int64 | float64](maxSize, maxScale int32, noMinMax, noSum bool, limit int, r func(attribute.Set) FilteredExemplarReservoir[N]) *expoHistogram[N] {
func newExponentialHistogram[N int64 | float64](
maxSize, maxScale int32,
noMinMax, noSum bool,
limit int,
r func(attribute.Set) FilteredExemplarReservoir[N],
) *expoHistogram[N] {
return &expoHistogram[N]{
noSum: noSum,
noMinMax: noMinMax,
@@ -314,7 +324,12 @@ type expoHistogram[N int64 | float64] struct {
start time.Time
}
func (e *expoHistogram[N]) measure(ctx context.Context, value N, fltrAttr attribute.Set, droppedAttr []attribute.KeyValue) {
func (e *expoHistogram[N]) measure(
ctx context.Context,
value N,
fltrAttr attribute.Set,
droppedAttr []attribute.KeyValue,
) {
// Ignore NaN and infinity.
if math.IsInf(float64(value), 0) || math.IsNaN(float64(value)) {
return
@@ -360,11 +375,19 @@ func (e *expoHistogram[N]) delta(dest *metricdata.Aggregation) int {
hDPts[i].ZeroThreshold = 0.0
hDPts[i].PositiveBucket.Offset = val.posBuckets.startBin
hDPts[i].PositiveBucket.Counts = reset(hDPts[i].PositiveBucket.Counts, len(val.posBuckets.counts), len(val.posBuckets.counts))
hDPts[i].PositiveBucket.Counts = reset(
hDPts[i].PositiveBucket.Counts,
len(val.posBuckets.counts),
len(val.posBuckets.counts),
)
copy(hDPts[i].PositiveBucket.Counts, val.posBuckets.counts)
hDPts[i].NegativeBucket.Offset = val.negBuckets.startBin
hDPts[i].NegativeBucket.Counts = reset(hDPts[i].NegativeBucket.Counts, len(val.negBuckets.counts), len(val.negBuckets.counts))
hDPts[i].NegativeBucket.Counts = reset(
hDPts[i].NegativeBucket.Counts,
len(val.negBuckets.counts),
len(val.negBuckets.counts),
)
copy(hDPts[i].NegativeBucket.Counts, val.negBuckets.counts)
if !e.noSum {
@@ -413,11 +436,19 @@ func (e *expoHistogram[N]) cumulative(dest *metricdata.Aggregation) int {
hDPts[i].ZeroThreshold = 0.0
hDPts[i].PositiveBucket.Offset = val.posBuckets.startBin
hDPts[i].PositiveBucket.Counts = reset(hDPts[i].PositiveBucket.Counts, len(val.posBuckets.counts), len(val.posBuckets.counts))
hDPts[i].PositiveBucket.Counts = reset(
hDPts[i].PositiveBucket.Counts,
len(val.posBuckets.counts),
len(val.posBuckets.counts),
)
copy(hDPts[i].PositiveBucket.Counts, val.posBuckets.counts)
hDPts[i].NegativeBucket.Offset = val.negBuckets.startBin
hDPts[i].NegativeBucket.Counts = reset(hDPts[i].NegativeBucket.Counts, len(val.negBuckets.counts), len(val.negBuckets.counts))
hDPts[i].NegativeBucket.Counts = reset(
hDPts[i].NegativeBucket.Counts,
len(val.negBuckets.counts),
len(val.negBuckets.counts),
)
copy(hDPts[i].NegativeBucket.Counts, val.negBuckets.counts)
if !e.noSum {

View File

@@ -1073,10 +1073,22 @@ func FuzzGetBin(f *testing.F) {
p.scale = (scale%31+31)%31 - 10
got := p.getBin(v)
if v <= lowerBound(got, p.scale) {
t.Errorf("v=%x scale =%d had bin %d, but was below lower bound %x", v, p.scale, got, lowerBound(got, p.scale))
t.Errorf(
"v=%x scale =%d had bin %d, but was below lower bound %x",
v,
p.scale,
got,
lowerBound(got, p.scale),
)
}
if v > lowerBound(got+1, p.scale) {
t.Errorf("v=%x scale =%d had bin %d, but was above upper bound %x", v, p.scale, got, lowerBound(got+1, p.scale))
t.Errorf(
"v=%x scale =%d had bin %d, but was above upper bound %x",
v,
p.scale,
got,
lowerBound(got+1, p.scale),
)
}
})
}

View File

@@ -33,7 +33,10 @@ type filteredExemplarReservoir[N int64 | float64] struct {
// NewFilteredExemplarReservoir creates a [FilteredExemplarReservoir] which only offers values
// that are allowed by the filter.
func NewFilteredExemplarReservoir[N int64 | float64](f exemplar.Filter, r exemplar.Reservoir) FilteredExemplarReservoir[N] {
func NewFilteredExemplarReservoir[N int64 | float64](
f exemplar.Filter,
r exemplar.Reservoir,
) FilteredExemplarReservoir[N] {
return &filteredExemplarReservoir[N]{
filter: f,
reservoir: r,

View File

@@ -53,7 +53,12 @@ type histValues[N int64 | float64] struct {
valuesMu sync.Mutex
}
func newHistValues[N int64 | float64](bounds []float64, noSum bool, limit int, r func(attribute.Set) FilteredExemplarReservoir[N]) *histValues[N] {
func newHistValues[N int64 | float64](
bounds []float64,
noSum bool,
limit int,
r func(attribute.Set) FilteredExemplarReservoir[N],
) *histValues[N] {
// The responsibility of keeping all buckets correctly associated with the
// passed boundaries is ultimately this type's responsibility. Make a copy
// here so we can always guarantee this. Or, in the case of failure, have
@@ -71,7 +76,12 @@ func newHistValues[N int64 | float64](bounds []float64, noSum bool, limit int, r
// Aggregate records the measurement value, scoped by attr, and aggregates it
// into a histogram.
func (s *histValues[N]) measure(ctx context.Context, value N, fltrAttr attribute.Set, droppedAttr []attribute.KeyValue) {
func (s *histValues[N]) measure(
ctx context.Context,
value N,
fltrAttr attribute.Set,
droppedAttr []attribute.KeyValue,
) {
// This search will return an index in the range [0, len(s.bounds)], where
// it will return len(s.bounds) if value is greater than the last element
// of s.bounds. This aligns with the buckets in that the length of buckets
@@ -108,7 +118,12 @@ func (s *histValues[N]) measure(ctx context.Context, value N, fltrAttr attribute
// newHistogram returns an Aggregator that summarizes a set of measurements as
// an histogram.
func newHistogram[N int64 | float64](boundaries []float64, noMinMax, noSum bool, limit int, r func(attribute.Set) FilteredExemplarReservoir[N]) *histogram[N] {
func newHistogram[N int64 | float64](
boundaries []float64,
noMinMax, noSum bool,
limit int,
r func(attribute.Set) FilteredExemplarReservoir[N],
) *histogram[N] {
return &histogram[N]{
histValues: newHistValues[N](boundaries, noSum, limit, r),
noMinMax: noMinMax,

View File

@@ -225,7 +225,12 @@ func testCumulativeHist[N int64 | float64](c conf[N]) func(t *testing.T) {
// hPointSummed returns an HistogramDataPoint that started and ended now with
// multi number of measurements values v. It includes a min and max (set to v).
func hPointSummed[N int64 | float64](a attribute.Set, v N, multi uint64, start, t time.Time) metricdata.HistogramDataPoint[N] {
func hPointSummed[N int64 | float64](
a attribute.Set,
v N,
multi uint64,
start, t time.Time,
) metricdata.HistogramDataPoint[N] {
idx := sort.SearchFloat64s(bounds, float64(v))
counts := make([]uint64, len(bounds)+1)
counts[idx] += multi
@@ -244,7 +249,12 @@ func hPointSummed[N int64 | float64](a attribute.Set, v N, multi uint64, start,
// hPoint returns an HistogramDataPoint that started and ended now with multi
// number of measurements values v. It includes a min and max (set to v).
func hPoint[N int64 | float64](a attribute.Set, v N, multi uint64, start, t time.Time) metricdata.HistogramDataPoint[N] {
func hPoint[N int64 | float64](
a attribute.Set,
v N,
multi uint64,
start, t time.Time,
) metricdata.HistogramDataPoint[N] {
idx := sort.SearchFloat64s(bounds, float64(v))
counts := make([]uint64, len(bounds)+1)
counts[idx] += multi
@@ -339,7 +349,12 @@ func TestCumulativeHistogramImmutableCounts(t *testing.T) {
cpCounts := make([]uint64, len(hdp.BucketCounts))
copy(cpCounts, hdp.BucketCounts)
hdp.BucketCounts[0] = 10
assert.Equal(t, cpCounts, h.values[alice.Equivalent()].counts, "modifying the Aggregator bucket counts should not change the Aggregator")
assert.Equal(
t,
cpCounts,
h.values[alice.Equivalent()].counts,
"modifying the Aggregator bucket counts should not change the Aggregator",
)
}
func TestDeltaHistogramReset(t *testing.T) {

View File

@@ -114,7 +114,10 @@ func (s *lastValue[N]) copyDpts(dest *[]metricdata.DataPoint[N], t time.Time) in
// newPrecomputedLastValue returns an aggregator that summarizes a set of
// observations as the last one made.
func newPrecomputedLastValue[N int64 | float64](limit int, r func(attribute.Set) FilteredExemplarReservoir[N]) *precomputedLastValue[N] {
func newPrecomputedLastValue[N int64 | float64](
limit int,
r func(attribute.Set) FilteredExemplarReservoir[N],
) *precomputedLastValue[N] {
return &precomputedLastValue[N]{lastValue: newLastValue[N](limit, r)}
}

View File

@@ -143,7 +143,11 @@ func (s *sum[N]) cumulative(dest *metricdata.Aggregation) int {
// newPrecomputedSum returns an aggregator that summarizes a set of
// observations as their arithmetic sum. Each sum is scoped by attributes and
// the aggregation cycle the measurements were made in.
func newPrecomputedSum[N int64 | float64](monotonic bool, limit int, r func(attribute.Set) FilteredExemplarReservoir[N]) *precomputedSum[N] {
func newPrecomputedSum[N int64 | float64](
monotonic bool,
limit int,
r func(attribute.Set) FilteredExemplarReservoir[N],
) *precomputedSum[N] {
return &precomputedSum[N]{
valueMap: newValueMap[N](limit, r),
monotonic: monotonic,

View File

@@ -58,7 +58,9 @@ func (mr *ManualReader) temporality(kind InstrumentKind) metricdata.Temporality
}
// aggregation returns what Aggregation to use for kind.
func (mr *ManualReader) aggregation(kind InstrumentKind) Aggregation { // nolint:revive // import-shadow for method scoped by type.
func (mr *ManualReader) aggregation(
kind InstrumentKind,
) Aggregation { // nolint:revive // import-shadow for method scoped by type.
return mr.aggregationSelector(kind)
}

View File

@@ -82,7 +82,10 @@ func (m *meter) Int64Counter(name string, options ...metric.Int64CounterOption)
// 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.
func (m *meter) Int64UpDownCounter(name string, options ...metric.Int64UpDownCounterOption) (metric.Int64UpDownCounter, error) {
func (m *meter) Int64UpDownCounter(
name string,
options ...metric.Int64UpDownCounterOption,
) (metric.Int64UpDownCounter, error) {
cfg := metric.NewInt64UpDownCounterConfig(options...)
const kind = InstrumentKindUpDownCounter
p := int64InstProvider{m}
@@ -174,7 +177,10 @@ func (m *meter) int64ObservableInstrument(id Instrument, callbacks []metric.Int6
// Description, and Unit, only the first set of callbacks provided are used.
// Use meter.RegisterCallback and Registration.Unregister to manage callbacks
// if instrumentation can be created multiple times with different callbacks.
func (m *meter) Int64ObservableCounter(name string, options ...metric.Int64ObservableCounterOption) (metric.Int64ObservableCounter, error) {
func (m *meter) Int64ObservableCounter(
name string,
options ...metric.Int64ObservableCounterOption,
) (metric.Int64ObservableCounter, error) {
cfg := metric.NewInt64ObservableCounterConfig(options...)
id := Instrument{
Name: name,
@@ -195,7 +201,10 @@ func (m *meter) Int64ObservableCounter(name string, options ...metric.Int64Obser
// Description, and Unit, only the first set of callbacks provided are used.
// Use meter.RegisterCallback and Registration.Unregister to manage callbacks
// if instrumentation can be created multiple times with different callbacks.
func (m *meter) Int64ObservableUpDownCounter(name string, options ...metric.Int64ObservableUpDownCounterOption) (metric.Int64ObservableUpDownCounter, error) {
func (m *meter) Int64ObservableUpDownCounter(
name string,
options ...metric.Int64ObservableUpDownCounterOption,
) (metric.Int64ObservableUpDownCounter, error) {
cfg := metric.NewInt64ObservableUpDownCounterConfig(options...)
id := Instrument{
Name: name,
@@ -216,7 +225,10 @@ func (m *meter) Int64ObservableUpDownCounter(name string, options ...metric.Int6
// Description, and Unit, only the first set of callbacks provided are used.
// Use meter.RegisterCallback and Registration.Unregister to manage callbacks
// if instrumentation can be created multiple times with different callbacks.
func (m *meter) Int64ObservableGauge(name string, options ...metric.Int64ObservableGaugeOption) (metric.Int64ObservableGauge, error) {
func (m *meter) Int64ObservableGauge(
name string,
options ...metric.Int64ObservableGaugeOption,
) (metric.Int64ObservableGauge, error) {
cfg := metric.NewInt64ObservableGaugeConfig(options...)
id := Instrument{
Name: name,
@@ -246,7 +258,10 @@ func (m *meter) Float64Counter(name string, options ...metric.Float64CounterOpti
// 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.
func (m *meter) Float64UpDownCounter(name string, options ...metric.Float64UpDownCounterOption) (metric.Float64UpDownCounter, error) {
func (m *meter) Float64UpDownCounter(
name string,
options ...metric.Float64UpDownCounterOption,
) (metric.Float64UpDownCounter, error) {
cfg := metric.NewFloat64UpDownCounterConfig(options...)
const kind = InstrumentKindUpDownCounter
p := float64InstProvider{m}
@@ -261,7 +276,10 @@ func (m *meter) Float64UpDownCounter(name string, options ...metric.Float64UpDow
// 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.
func (m *meter) Float64Histogram(name string, options ...metric.Float64HistogramOption) (metric.Float64Histogram, error) {
func (m *meter) Float64Histogram(
name string,
options ...metric.Float64HistogramOption,
) (metric.Float64Histogram, error) {
cfg := metric.NewFloat64HistogramConfig(options...)
p := float64InstProvider{m}
i, err := p.lookupHistogram(name, cfg)
@@ -289,7 +307,10 @@ func (m *meter) Float64Gauge(name string, options ...metric.Float64GaugeOption)
// float64ObservableInstrument returns a new observable identified by the Instrument.
// It registers callbacks for each reader's pipeline.
func (m *meter) float64ObservableInstrument(id Instrument, callbacks []metric.Float64Callback) (float64Observable, error) {
func (m *meter) float64ObservableInstrument(
id Instrument,
callbacks []metric.Float64Callback,
) (float64Observable, error) {
key := instID{
Name: id.Name,
Description: id.Description,
@@ -338,7 +359,10 @@ func (m *meter) float64ObservableInstrument(id Instrument, callbacks []metric.Fl
// Description, and Unit, only the first set of callbacks provided are used.
// Use meter.RegisterCallback and Registration.Unregister to manage callbacks
// if instrumentation can be created multiple times with different callbacks.
func (m *meter) Float64ObservableCounter(name string, options ...metric.Float64ObservableCounterOption) (metric.Float64ObservableCounter, error) {
func (m *meter) Float64ObservableCounter(
name string,
options ...metric.Float64ObservableCounterOption,
) (metric.Float64ObservableCounter, error) {
cfg := metric.NewFloat64ObservableCounterConfig(options...)
id := Instrument{
Name: name,
@@ -359,7 +383,10 @@ func (m *meter) Float64ObservableCounter(name string, options ...metric.Float64O
// Description, and Unit, only the first set of callbacks provided are used.
// Use meter.RegisterCallback and Registration.Unregister to manage callbacks
// if instrumentation can be created multiple times with different callbacks.
func (m *meter) Float64ObservableUpDownCounter(name string, options ...metric.Float64ObservableUpDownCounterOption) (metric.Float64ObservableUpDownCounter, error) {
func (m *meter) Float64ObservableUpDownCounter(
name string,
options ...metric.Float64ObservableUpDownCounterOption,
) (metric.Float64ObservableUpDownCounter, error) {
cfg := metric.NewFloat64ObservableUpDownCounterConfig(options...)
id := Instrument{
Name: name,
@@ -380,7 +407,10 @@ func (m *meter) Float64ObservableUpDownCounter(name string, options ...metric.Fl
// Description, and Unit, only the first set of callbacks provided are used.
// Use meter.RegisterCallback and Registration.Unregister to manage callbacks
// if instrumentation can be created multiple times with different callbacks.
func (m *meter) Float64ObservableGauge(name string, options ...metric.Float64ObservableGaugeOption) (metric.Float64ObservableGauge, error) {
func (m *meter) Float64ObservableGauge(
name string,
options ...metric.Float64ObservableGaugeOption,
) (metric.Float64ObservableGauge, error) {
cfg := metric.NewFloat64ObservableGaugeConfig(options...)
id := Instrument{
Name: name,
@@ -426,8 +456,10 @@ func warnRepeatedObservableCallbacks(id Instrument) {
"Instrument{Name: %q, Description: %q, Kind: %q, Unit: %q}",
id.Name, id.Description, "InstrumentKind"+id.Kind.String(), id.Unit,
)
global.Warn("Repeated observable instrument creation with callbacks. Ignoring new callbacks. Use meter.RegisterCallback and Registration.Unregister to manage callbacks.",
"instrument", inst,
global.Warn(
"Repeated observable instrument creation with callbacks. Ignoring new callbacks. Use meter.RegisterCallback and Registration.Unregister to manage callbacks.",
"instrument",
inst,
)
}
@@ -613,7 +645,10 @@ func (p int64InstProvider) aggs(kind InstrumentKind, name, desc, u string) ([]ag
return p.int64Resolver.Aggregators(inst)
}
func (p int64InstProvider) histogramAggs(name string, cfg metric.Int64HistogramConfig) ([]aggregate.Measure[int64], error) {
func (p int64InstProvider) histogramAggs(
name string,
cfg metric.Int64HistogramConfig,
) ([]aggregate.Measure[int64], error) {
boundaries := cfg.ExplicitBucketBoundaries()
aggError := AggregationExplicitBucketHistogram{Boundaries: boundaries}.err()
if aggError != nil {
@@ -671,7 +706,10 @@ func (p float64InstProvider) aggs(kind InstrumentKind, name, desc, u string) ([]
return p.float64Resolver.Aggregators(inst)
}
func (p float64InstProvider) histogramAggs(name string, cfg metric.Float64HistogramConfig) ([]aggregate.Measure[float64], error) {
func (p float64InstProvider) histogramAggs(
name string,
cfg metric.Float64HistogramConfig,
) ([]aggregate.Measure[float64], error) {
boundaries := cfg.ExplicitBucketBoundaries()
aggError := AggregationExplicitBucketHistogram{Boundaries: boundaries}.err()
if aggError != nil {

View File

@@ -441,9 +441,12 @@ func TestMeterCreatesInstruments(t *testing.T) {
Temporality: metricdata.CumulativeTemporality,
DataPoints: []metricdata.HistogramDataPoint[int64]{
{
Attributes: attribute.Set{},
Count: 1,
Bounds: []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000},
Attributes: attribute.Set{},
Count: 1,
Bounds: []float64{
0, 5, 10, 25, 50, 75, 100, 250, 500,
750, 1000, 2500, 5000, 7500, 10000,
},
BucketCounts: []uint64{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
Min: metricdata.NewExtrema[int64](7),
Max: metricdata.NewExtrema[int64](7),
@@ -511,9 +514,12 @@ func TestMeterCreatesInstruments(t *testing.T) {
Temporality: metricdata.CumulativeTemporality,
DataPoints: []metricdata.HistogramDataPoint[float64]{
{
Attributes: attribute.Set{},
Count: 1,
Bounds: []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000},
Attributes: attribute.Set{},
Count: 1,
Bounds: []float64{
0, 5, 10, 25, 50, 75, 100, 250, 500,
750, 1000, 2500, 5000, 7500, 10000,
},
BucketCounts: []uint64{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
Min: metricdata.NewExtrema[float64](7.),
Max: metricdata.NewExtrema[float64](7.),
@@ -1576,8 +1582,11 @@ func testAttributeFilter(temporality metricdata.Temporality) func(*testing.T) {
Data: metricdata.Histogram[float64]{
DataPoints: []metricdata.HistogramDataPoint[float64]{
{
Attributes: fooBar,
Bounds: []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000},
Attributes: fooBar,
Bounds: []float64{
0, 5, 10, 25, 50, 75, 100, 250, 500,
750, 1000, 2500, 5000, 7500, 10000,
},
BucketCounts: []uint64{0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
Count: 2,
Min: metricdata.NewExtrema(1.),
@@ -1652,8 +1661,11 @@ func testAttributeFilter(temporality metricdata.Temporality) func(*testing.T) {
Data: metricdata.Histogram[int64]{
DataPoints: []metricdata.HistogramDataPoint[int64]{
{
Attributes: fooBar,
Bounds: []float64{0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000},
Attributes: fooBar,
Bounds: []float64{
0, 5, 10, 25, 50, 75, 100, 250, 500,
750, 1000, 2500, 5000, 7500, 10000,
},
BucketCounts: []uint64{0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
Count: 2,
Min: metricdata.NewExtrema[int64](1),
@@ -1689,7 +1701,12 @@ func testAttributeFilter(temporality metricdata.Temporality) func(*testing.T) {
require.Len(t, m.ScopeMetrics, 1)
require.Len(t, m.ScopeMetrics[0].Metrics, 1)
metricdatatest.AssertEqual(t, tt.wantMetric, m.ScopeMetrics[0].Metrics[0], metricdatatest.IgnoreTimestamp())
metricdatatest.AssertEqual(
t,
tt.wantMetric,
m.ScopeMetrics[0].Metrics[0],
metricdatatest.IgnoreTimestamp(),
)
})
}
}
@@ -2119,7 +2136,15 @@ func TestMalformedSelectors(t *testing.T) {
obs.ObserveFloat64(afGauge, 1)
return nil
}
_, err = meter.RegisterCallback(callback, aiCounter, aiUpDownCounter, aiGauge, afCounter, afUpDownCounter, afGauge)
_, err = meter.RegisterCallback(
callback,
aiCounter,
aiUpDownCounter,
aiGauge,
afCounter,
afUpDownCounter,
afGauge,
)
require.NoError(t, err)
siCounter.Add(context.Background(), 1)
@@ -2182,7 +2207,10 @@ func TestHistogramBucketPrecedenceOrdering(t *testing.T) {
},
} {
t.Run(tt.desc, func(t *testing.T) {
meter := NewMeterProvider(WithView(tt.views...), WithReader(tt.reader)).Meter("TestHistogramBucketPrecedenceOrdering")
meter := NewMeterProvider(
WithView(tt.views...),
WithReader(tt.reader),
).Meter("TestHistogramBucketPrecedenceOrdering")
sfHistogram, err := meter.Float64Histogram("sync.float64.histogram", tt.histogramOpts...)
require.NoError(t, err)
sfHistogram.Record(context.Background(), 1)
@@ -2508,7 +2536,15 @@ func TestDuplicateInstrumentCreation(t *testing.T) {
internalMeter, ok := m.(*meter)
require.True(t, ok)
// check that multiple calls to create the same instrument only create 1 instrument
numInstruments := len(internalMeter.int64Insts.data) + len(internalMeter.float64Insts.data) + len(internalMeter.int64ObservableInsts.data) + len(internalMeter.float64ObservableInsts.data)
numInstruments := len(
internalMeter.int64Insts.data,
) + len(
internalMeter.float64Insts.data,
) + len(
internalMeter.int64ObservableInsts.data,
) + len(
internalMeter.float64ObservableInsts.data,
)
require.Equal(t, 1, numInstruments)
})
}

View File

@@ -680,18 +680,44 @@ func TestAssertEqual(t *testing.T) {
t.Run("SumFloat64", testDatatype(sumFloat64A, sumFloat64B, equalSums[float64]))
t.Run("GaugeInt64", testDatatype(gaugeInt64A, gaugeInt64B, equalGauges[int64]))
t.Run("GaugeFloat64", testDatatype(gaugeFloat64A, gaugeFloat64B, equalGauges[float64]))
t.Run("HistogramDataPointInt64", testDatatype(histogramDataPointInt64A, histogramDataPointInt64B, equalHistogramDataPoints[int64]))
t.Run("HistogramDataPointFloat64", testDatatype(histogramDataPointFloat64A, histogramDataPointFloat64B, equalHistogramDataPoints[float64]))
t.Run(
"HistogramDataPointInt64",
testDatatype(histogramDataPointInt64A, histogramDataPointInt64B, equalHistogramDataPoints[int64]),
)
t.Run(
"HistogramDataPointFloat64",
testDatatype(histogramDataPointFloat64A, histogramDataPointFloat64B, equalHistogramDataPoints[float64]),
)
t.Run("DataPointInt64", testDatatype(dataPointInt64A, dataPointInt64B, equalDataPoints[int64]))
t.Run("DataPointFloat64", testDatatype(dataPointFloat64A, dataPointFloat64B, equalDataPoints[float64]))
t.Run("ExtremaInt64", testDatatype(minInt64A, minInt64B, equalExtrema[int64]))
t.Run("ExtremaFloat64", testDatatype(minFloat64A, minFloat64B, equalExtrema[float64]))
t.Run("ExemplarInt64", testDatatype(exemplarInt64A, exemplarInt64B, equalExemplars[int64]))
t.Run("ExemplarFloat64", testDatatype(exemplarFloat64A, exemplarFloat64B, equalExemplars[float64]))
t.Run("ExponentialHistogramInt64", testDatatype(exponentialHistogramInt64A, exponentialHistogramInt64B, equalExponentialHistograms[int64]))
t.Run("ExponentialHistogramFloat64", testDatatype(exponentialHistogramFloat64A, exponentialHistogramFloat64B, equalExponentialHistograms[float64]))
t.Run("ExponentialHistogramDataPointInt64", testDatatype(exponentialHistogramDataPointInt64A, exponentialHistogramDataPointInt64B, equalExponentialHistogramDataPoints[int64]))
t.Run("ExponentialHistogramDataPointFloat64", testDatatype(exponentialHistogramDataPointFloat64A, exponentialHistogramDataPointFloat64B, equalExponentialHistogramDataPoints[float64]))
t.Run(
"ExponentialHistogramInt64",
testDatatype(exponentialHistogramInt64A, exponentialHistogramInt64B, equalExponentialHistograms[int64]),
)
t.Run(
"ExponentialHistogramFloat64",
testDatatype(exponentialHistogramFloat64A, exponentialHistogramFloat64B, equalExponentialHistograms[float64]),
)
t.Run(
"ExponentialHistogramDataPointInt64",
testDatatype(
exponentialHistogramDataPointInt64A,
exponentialHistogramDataPointInt64B,
equalExponentialHistogramDataPoints[int64],
),
)
t.Run(
"ExponentialHistogramDataPointFloat64",
testDatatype(
exponentialHistogramDataPointFloat64A,
exponentialHistogramDataPointFloat64B,
equalExponentialHistogramDataPoints[float64],
),
)
t.Run("ExponentialBuckets", testDatatype(exponentialBucket2, exponentialBucket3, equalExponentialBuckets))
t.Run("Summary", testDatatype(summaryA, summaryB, equalSummary))
t.Run("SummaryDataPoint", testDatatype(summaryDataPointA, summaryDataPointB, equalSummaryDataPoint))
@@ -708,18 +734,56 @@ func TestAssertEqualIgnoreTime(t *testing.T) {
t.Run("SumFloat64", testDatatypeIgnoreTime(sumFloat64A, sumFloat64C, equalSums[float64]))
t.Run("GaugeInt64", testDatatypeIgnoreTime(gaugeInt64A, gaugeInt64C, equalGauges[int64]))
t.Run("GaugeFloat64", testDatatypeIgnoreTime(gaugeFloat64A, gaugeFloat64C, equalGauges[float64]))
t.Run("HistogramDataPointInt64", testDatatypeIgnoreTime(histogramDataPointInt64A, histogramDataPointInt64C, equalHistogramDataPoints[int64]))
t.Run("HistogramDataPointFloat64", testDatatypeIgnoreTime(histogramDataPointFloat64A, histogramDataPointFloat64C, equalHistogramDataPoints[float64]))
t.Run(
"HistogramDataPointInt64",
testDatatypeIgnoreTime(histogramDataPointInt64A, histogramDataPointInt64C, equalHistogramDataPoints[int64]),
)
t.Run(
"HistogramDataPointFloat64",
testDatatypeIgnoreTime(
histogramDataPointFloat64A,
histogramDataPointFloat64C,
equalHistogramDataPoints[float64],
),
)
t.Run("DataPointInt64", testDatatypeIgnoreTime(dataPointInt64A, dataPointInt64C, equalDataPoints[int64]))
t.Run("DataPointFloat64", testDatatypeIgnoreTime(dataPointFloat64A, dataPointFloat64C, equalDataPoints[float64]))
t.Run("ExtremaInt64", testDatatypeIgnoreTime(minInt64A, minInt64C, equalExtrema[int64]))
t.Run("ExtremaFloat64", testDatatypeIgnoreTime(minFloat64A, minFloat64C, equalExtrema[float64]))
t.Run("ExemplarInt64", testDatatypeIgnoreTime(exemplarInt64A, exemplarInt64C, equalExemplars[int64]))
t.Run("ExemplarFloat64", testDatatypeIgnoreTime(exemplarFloat64A, exemplarFloat64C, equalExemplars[float64]))
t.Run("ExponentialHistogramInt64", testDatatypeIgnoreTime(exponentialHistogramInt64A, exponentialHistogramInt64C, equalExponentialHistograms[int64]))
t.Run("ExponentialHistogramFloat64", testDatatypeIgnoreTime(exponentialHistogramFloat64A, exponentialHistogramFloat64C, equalExponentialHistograms[float64]))
t.Run("ExponentialHistogramDataPointInt64", testDatatypeIgnoreTime(exponentialHistogramDataPointInt64A, exponentialHistogramDataPointInt64C, equalExponentialHistogramDataPoints[int64]))
t.Run("ExponentialHistogramDataPointFloat64", testDatatypeIgnoreTime(exponentialHistogramDataPointFloat64A, exponentialHistogramDataPointFloat64C, equalExponentialHistogramDataPoints[float64]))
t.Run(
"ExponentialHistogramInt64",
testDatatypeIgnoreTime(
exponentialHistogramInt64A,
exponentialHistogramInt64C,
equalExponentialHistograms[int64],
),
)
t.Run(
"ExponentialHistogramFloat64",
testDatatypeIgnoreTime(
exponentialHistogramFloat64A,
exponentialHistogramFloat64C,
equalExponentialHistograms[float64],
),
)
t.Run(
"ExponentialHistogramDataPointInt64",
testDatatypeIgnoreTime(
exponentialHistogramDataPointInt64A,
exponentialHistogramDataPointInt64C,
equalExponentialHistogramDataPoints[int64],
),
)
t.Run(
"ExponentialHistogramDataPointFloat64",
testDatatypeIgnoreTime(
exponentialHistogramDataPointFloat64A,
exponentialHistogramDataPointFloat64C,
equalExponentialHistogramDataPoints[float64],
),
)
t.Run("Summary", testDatatypeIgnoreTime(summaryA, summaryC, equalSummary))
t.Run("SummaryDataPoint", testDatatypeIgnoreTime(summaryDataPointA, summaryDataPointC, equalSummaryDataPoint))
}
@@ -727,11 +791,17 @@ func TestAssertEqualIgnoreTime(t *testing.T) {
func TestAssertEqualIgnoreExemplars(t *testing.T) {
hdpInt64 := histogramDataPointInt64A
hdpInt64.Exemplars = []metricdata.Exemplar[int64]{exemplarInt64B}
t.Run("HistogramDataPointInt64", testDatatypeIgnoreExemplars(histogramDataPointInt64A, hdpInt64, equalHistogramDataPoints[int64]))
t.Run(
"HistogramDataPointInt64",
testDatatypeIgnoreExemplars(histogramDataPointInt64A, hdpInt64, equalHistogramDataPoints[int64]),
)
hdpFloat64 := histogramDataPointFloat64A
hdpFloat64.Exemplars = []metricdata.Exemplar[float64]{exemplarFloat64B}
t.Run("HistogramDataPointFloat64", testDatatypeIgnoreExemplars(histogramDataPointFloat64A, hdpFloat64, equalHistogramDataPoints[float64]))
t.Run(
"HistogramDataPointFloat64",
testDatatypeIgnoreExemplars(histogramDataPointFloat64A, hdpFloat64, equalHistogramDataPoints[float64]),
)
dpInt64 := dataPointInt64A
dpInt64.Exemplars = []metricdata.Exemplar[int64]{exemplarInt64B}
@@ -743,11 +813,25 @@ func TestAssertEqualIgnoreExemplars(t *testing.T) {
ehdpInt64 := exponentialHistogramDataPointInt64A
ehdpInt64.Exemplars = []metricdata.Exemplar[int64]{exemplarInt64B}
t.Run("ExponentialHistogramDataPointInt64", testDatatypeIgnoreExemplars(exponentialHistogramDataPointInt64A, ehdpInt64, equalExponentialHistogramDataPoints[int64]))
t.Run(
"ExponentialHistogramDataPointInt64",
testDatatypeIgnoreExemplars(
exponentialHistogramDataPointInt64A,
ehdpInt64,
equalExponentialHistogramDataPoints[int64],
),
)
ehdpFloat64 := exponentialHistogramDataPointFloat64A
ehdpFloat64.Exemplars = []metricdata.Exemplar[float64]{exemplarFloat64B}
t.Run("ExponentialHistogramDataPointFloat64", testDatatypeIgnoreExemplars(exponentialHistogramDataPointFloat64A, ehdpFloat64, equalExponentialHistogramDataPoints[float64]))
t.Run(
"ExponentialHistogramDataPointFloat64",
testDatatypeIgnoreExemplars(
exponentialHistogramDataPointFloat64A,
ehdpFloat64,
equalExponentialHistogramDataPoints[float64],
),
)
}
func TestAssertEqualIgnoreValue(t *testing.T) {
@@ -760,16 +844,54 @@ func TestAssertEqualIgnoreValue(t *testing.T) {
t.Run("SumFloat64", testDatatypeIgnoreValue(sumFloat64A, sumFloat64D, equalSums[float64]))
t.Run("GaugeInt64", testDatatypeIgnoreValue(gaugeInt64A, gaugeInt64D, equalGauges[int64]))
t.Run("GaugeFloat64", testDatatypeIgnoreValue(gaugeFloat64A, gaugeFloat64D, equalGauges[float64]))
t.Run("HistogramDataPointInt64", testDatatypeIgnoreValue(histogramDataPointInt64A, histogramDataPointInt64D, equalHistogramDataPoints[int64]))
t.Run("HistogramDataPointFloat64", testDatatypeIgnoreValue(histogramDataPointFloat64A, histogramDataPointFloat64D, equalHistogramDataPoints[float64]))
t.Run(
"HistogramDataPointInt64",
testDatatypeIgnoreValue(histogramDataPointInt64A, histogramDataPointInt64D, equalHistogramDataPoints[int64]),
)
t.Run(
"HistogramDataPointFloat64",
testDatatypeIgnoreValue(
histogramDataPointFloat64A,
histogramDataPointFloat64D,
equalHistogramDataPoints[float64],
),
)
t.Run("DataPointInt64", testDatatypeIgnoreValue(dataPointInt64A, dataPointInt64D, equalDataPoints[int64]))
t.Run("DataPointFloat64", testDatatypeIgnoreValue(dataPointFloat64A, dataPointFloat64D, equalDataPoints[float64]))
t.Run("ExemplarInt64", testDatatypeIgnoreValue(exemplarInt64A, exemplarInt64D, equalExemplars[int64]))
t.Run("ExemplarFloat64", testDatatypeIgnoreValue(exemplarFloat64A, exemplarFloat64D, equalExemplars[float64]))
t.Run("ExponentialHistogramInt64", testDatatypeIgnoreValue(exponentialHistogramInt64A, exponentialHistogramInt64D, equalExponentialHistograms[int64]))
t.Run("ExponentialHistogramFloat64", testDatatypeIgnoreValue(exponentialHistogramFloat64A, exponentialHistogramFloat64D, equalExponentialHistograms[float64]))
t.Run("ExponentialHistogramDataPointInt64", testDatatypeIgnoreValue(exponentialHistogramDataPointInt64A, exponentialHistogramDataPointInt64D, equalExponentialHistogramDataPoints[int64]))
t.Run("ExponentialHistogramDataPointFloat64", testDatatypeIgnoreValue(exponentialHistogramDataPointFloat64A, exponentialHistogramDataPointFloat64D, equalExponentialHistogramDataPoints[float64]))
t.Run(
"ExponentialHistogramInt64",
testDatatypeIgnoreValue(
exponentialHistogramInt64A,
exponentialHistogramInt64D,
equalExponentialHistograms[int64],
),
)
t.Run(
"ExponentialHistogramFloat64",
testDatatypeIgnoreValue(
exponentialHistogramFloat64A,
exponentialHistogramFloat64D,
equalExponentialHistograms[float64],
),
)
t.Run(
"ExponentialHistogramDataPointInt64",
testDatatypeIgnoreValue(
exponentialHistogramDataPointInt64A,
exponentialHistogramDataPointInt64D,
equalExponentialHistogramDataPoints[int64],
),
)
t.Run(
"ExponentialHistogramDataPointFloat64",
testDatatypeIgnoreValue(
exponentialHistogramDataPointFloat64A,
exponentialHistogramDataPointFloat64D,
equalExponentialHistogramDataPoints[float64],
),
)
t.Run("Summary", testDatatypeIgnoreValue(summaryA, summaryD, equalSummary))
t.Run("SummaryDataPoint", testDatatypeIgnoreValue(summaryDataPointA, summaryDataPointD, equalSummaryDataPoint))
}
@@ -854,7 +976,13 @@ func TestAssertAggregationsEqual(t *testing.T) {
assert.Empty(t, r, "value should be ignored: %v == %v", histogramFloat64A, histogramFloat64D)
r = equalAggregations(exponentialHistogramInt64A, exponentialHistogramInt64B, config{})
assert.NotEmptyf(t, r, "exponential histograms should not be equal: %v == %v", exponentialHistogramInt64A, exponentialHistogramInt64B)
assert.NotEmptyf(
t,
r,
"exponential histograms should not be equal: %v == %v",
exponentialHistogramInt64A,
exponentialHistogramInt64B,
)
r = equalAggregations(exponentialHistogramInt64A, exponentialHistogramInt64C, config{ignoreTimestamp: true})
assert.Empty(t, r, "exponential histograms should be equal: %v", r)
@@ -863,7 +991,13 @@ func TestAssertAggregationsEqual(t *testing.T) {
assert.Empty(t, r, "value should be ignored: %v == %v", exponentialHistogramInt64A, exponentialHistogramInt64D)
r = equalAggregations(exponentialHistogramFloat64A, exponentialHistogramFloat64B, config{})
assert.NotEmptyf(t, r, "exponential histograms should not be equal: %v == %v", exponentialHistogramFloat64A, exponentialHistogramFloat64B)
assert.NotEmptyf(
t,
r,
"exponential histograms should not be equal: %v == %v",
exponentialHistogramFloat64A,
exponentialHistogramFloat64B,
)
r = equalAggregations(exponentialHistogramFloat64A, exponentialHistogramFloat64C, config{ignoreTimestamp: true})
assert.Empty(t, r, "exponential histograms should be equal: %v", r)

View File

@@ -230,7 +230,10 @@ func equalHistograms[N int64 | float64](a, b metricdata.Histogram[N], cfg config
// equalDataPoints returns reasons DataPoints are not equal. If they are
// equal, the returned reasons will be empty.
func equalDataPoints[N int64 | float64](a, b metricdata.DataPoint[N], cfg config) (reasons []string) { // nolint: revive // Intentional internal control flag
func equalDataPoints[N int64 | float64](
a, b metricdata.DataPoint[N],
cfg config,
) (reasons []string) { // nolint: revive // Intentional internal control flag
if !a.Attributes.Equals(&b.Attributes) {
reasons = append(reasons, notEqualStr(
"Attributes",
@@ -272,7 +275,10 @@ func equalDataPoints[N int64 | float64](a, b metricdata.DataPoint[N], cfg config
// equalHistogramDataPoints returns reasons HistogramDataPoints are not equal.
// If they are equal, the returned reasons will be empty.
func equalHistogramDataPoints[N int64 | float64](a, b metricdata.HistogramDataPoint[N], cfg config) (reasons []string) { // nolint: revive // Intentional internal control flag
func equalHistogramDataPoints[N int64 | float64](
a, b metricdata.HistogramDataPoint[N],
cfg config,
) (reasons []string) { // nolint: revive // Intentional internal control flag
if !a.Attributes.Equals(&b.Attributes) {
reasons = append(reasons, notEqualStr(
"Attributes",
@@ -329,7 +335,10 @@ func equalHistogramDataPoints[N int64 | float64](a, b metricdata.HistogramDataPo
//
// The DataPoints each Histogram contains are compared based on containing the
// same HistogramDataPoint, not the order they are stored in.
func equalExponentialHistograms[N int64 | float64](a, b metricdata.ExponentialHistogram[N], cfg config) (reasons []string) {
func equalExponentialHistograms[N int64 | float64](
a, b metricdata.ExponentialHistogram[N],
cfg config,
) (reasons []string) {
if a.Temporality != b.Temporality {
reasons = append(reasons, notEqualStr("Temporality", a.Temporality, b.Temporality))
}
@@ -350,7 +359,10 @@ func equalExponentialHistograms[N int64 | float64](a, b metricdata.ExponentialHi
// equalExponentialHistogramDataPoints returns reasons HistogramDataPoints are not equal.
// If they are equal, the returned reasons will be empty.
func equalExponentialHistogramDataPoints[N int64 | float64](a, b metricdata.ExponentialHistogramDataPoint[N], cfg config) (reasons []string) { // nolint: revive // Intentional internal control flag
func equalExponentialHistogramDataPoints[N int64 | float64](
a, b metricdata.ExponentialHistogramDataPoint[N],
cfg config,
) (reasons []string) { // nolint: revive // Intentional internal control flag
if !a.Attributes.Equals(&b.Attributes) {
reasons = append(reasons, notEqualStr(
"Attributes",
@@ -637,7 +649,10 @@ func missingAttrStr(name string) string {
return "missing attribute " + name
}
func hasAttributesExemplars[T int64 | float64](exemplar metricdata.Exemplar[T], attrs ...attribute.KeyValue) (reasons []string) {
func hasAttributesExemplars[T int64 | float64](
exemplar metricdata.Exemplar[T],
attrs ...attribute.KeyValue,
) (reasons []string) {
s := attribute.NewSet(exemplar.FilteredAttributes...)
for _, attr := range attrs {
val, ok := s.Value(attr.Key)
@@ -652,7 +667,10 @@ func hasAttributesExemplars[T int64 | float64](exemplar metricdata.Exemplar[T],
return reasons
}
func hasAttributesDataPoints[T int64 | float64](dp metricdata.DataPoint[T], attrs ...attribute.KeyValue) (reasons []string) {
func hasAttributesDataPoints[T int64 | float64](
dp metricdata.DataPoint[T],
attrs ...attribute.KeyValue,
) (reasons []string) {
for _, attr := range attrs {
val, ok := dp.Attributes.Value(attr.Key)
if !ok {
@@ -688,7 +706,10 @@ func hasAttributesSum[T int64 | float64](sum metricdata.Sum[T], attrs ...attribu
return reasons
}
func hasAttributesHistogramDataPoints[T int64 | float64](dp metricdata.HistogramDataPoint[T], attrs ...attribute.KeyValue) (reasons []string) {
func hasAttributesHistogramDataPoints[T int64 | float64](
dp metricdata.HistogramDataPoint[T],
attrs ...attribute.KeyValue,
) (reasons []string) {
for _, attr := range attrs {
val, ok := dp.Attributes.Value(attr.Key)
if !ok {
@@ -702,7 +723,10 @@ func hasAttributesHistogramDataPoints[T int64 | float64](dp metricdata.Histogram
return reasons
}
func hasAttributesHistogram[T int64 | float64](histogram metricdata.Histogram[T], attrs ...attribute.KeyValue) (reasons []string) {
func hasAttributesHistogram[T int64 | float64](
histogram metricdata.Histogram[T],
attrs ...attribute.KeyValue,
) (reasons []string) {
for n, dp := range histogram.DataPoints {
reas := hasAttributesHistogramDataPoints(dp, attrs...)
if len(reas) > 0 {
@@ -713,7 +737,10 @@ func hasAttributesHistogram[T int64 | float64](histogram metricdata.Histogram[T]
return reasons
}
func hasAttributesExponentialHistogramDataPoints[T int64 | float64](dp metricdata.ExponentialHistogramDataPoint[T], attrs ...attribute.KeyValue) (reasons []string) {
func hasAttributesExponentialHistogramDataPoints[T int64 | float64](
dp metricdata.ExponentialHistogramDataPoint[T],
attrs ...attribute.KeyValue,
) (reasons []string) {
for _, attr := range attrs {
val, ok := dp.Attributes.Value(attr.Key)
if !ok {
@@ -727,7 +754,10 @@ func hasAttributesExponentialHistogramDataPoints[T int64 | float64](dp metricdat
return reasons
}
func hasAttributesExponentialHistogram[T int64 | float64](histogram metricdata.ExponentialHistogram[T], attrs ...attribute.KeyValue) (reasons []string) {
func hasAttributesExponentialHistogram[T int64 | float64](
histogram metricdata.ExponentialHistogram[T],
attrs ...attribute.KeyValue,
) (reasons []string) {
for n, dp := range histogram.DataPoints {
reas := hasAttributesExponentialHistogramDataPoints(dp, attrs...)
if len(reas) > 0 {

View File

@@ -193,7 +193,9 @@ func (r *PeriodicReader) temporality(kind InstrumentKind) metricdata.Temporality
}
// aggregation returns what Aggregation to use for kind.
func (r *PeriodicReader) aggregation(kind InstrumentKind) Aggregation { // nolint:revive // import-shadow for method scoped by type.
func (r *PeriodicReader) aggregation(
kind InstrumentKind,
) Aggregation { // nolint:revive // import-shadow for method scoped by type.
return r.exporter.Aggregation(kind)
}

View File

@@ -347,7 +347,12 @@ func (i *inserter[N]) readerDefaultAggregation(kind InstrumentKind) Aggregation
//
// If the instrument defines an unknown or incompatible aggregation, an error
// is returned.
func (i *inserter[N]) cachedAggregator(scope instrumentation.Scope, kind InstrumentKind, stream Stream, readerAggregation Aggregation) (meas aggregate.Measure[N], aggID uint64, err error) {
func (i *inserter[N]) cachedAggregator(
scope instrumentation.Scope,
kind InstrumentKind,
stream Stream,
readerAggregation Aggregation,
) (meas aggregate.Measure[N], aggID uint64, err error) {
switch stream.Aggregation.(type) {
case nil:
// The aggregation was not overridden with a view. Use the aggregation
@@ -379,8 +384,11 @@ func (i *inserter[N]) cachedAggregator(scope instrumentation.Scope, kind Instrum
normID := id.normalize()
cv := i.aggregators.Lookup(normID, func() aggVal[N] {
b := aggregate.Builder[N]{
Temporality: i.pipeline.reader.temporality(kind),
ReservoirFunc: reservoirFunc[N](stream.ExemplarReservoirProviderSelector(stream.Aggregation), i.pipeline.exemplarFilter),
Temporality: i.pipeline.reader.temporality(kind),
ReservoirFunc: reservoirFunc[N](
stream.ExemplarReservoirProviderSelector(stream.Aggregation),
i.pipeline.exemplarFilter,
),
}
b.Filter = stream.AttributeFilter
// A value less than or equal to zero will disable the aggregation
@@ -471,7 +479,11 @@ func (i *inserter[N]) instID(kind InstrumentKind, stream Stream) instID {
// aggregateFunc returns new aggregate functions matching agg, kind, and
// monotonic. If the agg is unknown or temporality is invalid, an error is
// returned.
func (i *inserter[N]) aggregateFunc(b aggregate.Builder[N], agg Aggregation, kind InstrumentKind) (meas aggregate.Measure[N], comp aggregate.ComputeAggregation, err error) {
func (i *inserter[N]) aggregateFunc(
b aggregate.Builder[N],
agg Aggregation,
kind InstrumentKind,
) (meas aggregate.Measure[N], comp aggregate.ComputeAggregation, err error) {
switch a := agg.(type) {
case AggregationDefault:
return i.aggregateFunc(b, DefaultAggregationSelector(kind), kind)

View File

@@ -34,14 +34,25 @@ func (invalidAggregation) err() error {
return nil
}
func requireN[N int64 | float64](t *testing.T, n int, m []aggregate.Measure[N], comps []aggregate.ComputeAggregation, err error) {
func requireN[N int64 | float64](
t *testing.T,
n int,
m []aggregate.Measure[N],
comps []aggregate.ComputeAggregation,
err error,
) {
t.Helper()
assert.NoError(t, err)
require.Len(t, m, n)
require.Len(t, comps, n)
}
func assertSum[N int64 | float64](n int, temp metricdata.Temporality, mono bool, v [2]N) func(*testing.T, []aggregate.Measure[N], []aggregate.ComputeAggregation, error) {
func assertSum[N int64 | float64](
n int,
temp metricdata.Temporality,
mono bool,
v [2]N,
) func(*testing.T, []aggregate.Measure[N], []aggregate.ComputeAggregation, error) {
return func(t *testing.T, meas []aggregate.Measure[N], comps []aggregate.ComputeAggregation, err error) {
t.Helper()
requireN[N](t, n, meas, comps, err)
@@ -71,7 +82,9 @@ func assertSum[N int64 | float64](n int, temp metricdata.Temporality, mono bool,
}
}
func assertHist[N int64 | float64](temp metricdata.Temporality) func(*testing.T, []aggregate.Measure[N], []aggregate.ComputeAggregation, error) {
func assertHist[N int64 | float64](
temp metricdata.Temporality,
) func(*testing.T, []aggregate.Measure[N], []aggregate.ComputeAggregation, error) {
return func(t *testing.T, meas []aggregate.Measure[N], comps []aggregate.ComputeAggregation, err error) {
t.Helper()
requireN[N](t, 1, meas, comps, err)
@@ -116,7 +129,12 @@ func assertHist[N int64 | float64](temp metricdata.Temporality) func(*testing.T,
}
}
func assertLastValue[N int64 | float64](t *testing.T, meas []aggregate.Measure[N], comps []aggregate.ComputeAggregation, err error) {
func assertLastValue[N int64 | float64](
t *testing.T,
meas []aggregate.Measure[N],
comps []aggregate.ComputeAggregation,
err error,
) {
t.Helper()
requireN[N](t, 1, meas, comps, err)
@@ -164,9 +182,11 @@ func testCreateAggregators[N int64 | float64](t *testing.T) {
validate func(*testing.T, []aggregate.Measure[N], []aggregate.ComputeAggregation, error)
}{
{
name: "Default/Drop",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDrop{} })),
inst: instruments[InstrumentKindCounter],
name: "Default/Drop",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDrop{} }),
),
inst: instruments[InstrumentKindCounter],
validate: func(t *testing.T, meas []aggregate.Measure[N], comps []aggregate.ComputeAggregation, err error) {
t.Helper()
assert.NoError(t, err)
@@ -304,44 +324,58 @@ func testCreateAggregators[N int64 | float64](t *testing.T) {
validate: assertSum[N](2, metricdata.CumulativeTemporality, true, [2]N{1, 4}),
},
{
name: "Reader/Default/Cumulative/Sum/Monotonic",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Cumulative/Sum/Monotonic",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindCounter],
validate: assertSum[N](1, metricdata.CumulativeTemporality, true, [2]N{1, 4}),
},
{
name: "Reader/Default/Cumulative/Sum/NonMonotonic",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Cumulative/Sum/NonMonotonic",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindUpDownCounter],
validate: assertSum[N](1, metricdata.CumulativeTemporality, false, [2]N{1, 4}),
},
{
name: "Reader/Default/Cumulative/ExplicitBucketHistogram",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Cumulative/ExplicitBucketHistogram",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindHistogram],
validate: assertHist[N](metricdata.CumulativeTemporality),
},
{
name: "Reader/Default/Cumulative/Gauge",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Cumulative/Gauge",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindGauge],
validate: assertLastValue[N],
},
{
name: "Reader/Default/Cumulative/PrecomputedSum/Monotonic",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Cumulative/PrecomputedSum/Monotonic",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindObservableCounter],
validate: assertSum[N](1, metricdata.CumulativeTemporality, true, [2]N{1, 3}),
},
{
name: "Reader/Default/Cumulative/PrecomputedSum/NonMonotonic",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Cumulative/PrecomputedSum/NonMonotonic",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindObservableUpDownCounter],
validate: assertSum[N](1, metricdata.CumulativeTemporality, false, [2]N{1, 3}),
},
{
name: "Reader/Default/Gauge",
reader: NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} })),
name: "Reader/Default/Gauge",
reader: NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationDefault{} }),
),
inst: instruments[InstrumentKindObservableGauge],
validate: assertLastValue[N],
},
@@ -418,7 +452,9 @@ func TestPipelinesAggregatorForEachReader(t *testing.T) {
func TestPipelineRegistryCreateAggregators(t *testing.T) {
renameView := NewView(Instrument{Name: "foo"}, Stream{Name: "bar"})
testRdr := NewManualReader()
testRdrHistogram := NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationExplicitBucketHistogram{} }))
testRdrHistogram := NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationExplicitBucketHistogram{} }),
)
testCases := []struct {
name string
@@ -529,7 +565,9 @@ func TestPipelineRegistryResource(t *testing.T) {
}
func TestPipelineRegistryCreateAggregatorsIncompatibleInstrument(t *testing.T) {
testRdrHistogram := NewManualReader(WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationSum{} }))
testRdrHistogram := NewManualReader(
WithAggregationSelector(func(ik InstrumentKind) Aggregation { return AggregationSum{} }),
)
readers := []Reader{testRdrHistogram}
views := []View{defaultView}

View File

@@ -146,7 +146,10 @@ type AggregationSelector func(InstrumentKind) Aggregation
// Histogram ⇨ ExplicitBucketHistogram.
func DefaultAggregationSelector(ik InstrumentKind) Aggregation {
switch ik {
case InstrumentKindCounter, InstrumentKindUpDownCounter, InstrumentKindObservableCounter, InstrumentKindObservableUpDownCounter:
case InstrumentKindCounter,
InstrumentKindUpDownCounter,
InstrumentKindObservableCounter,
InstrumentKindObservableUpDownCounter:
return AggregationSum{}
case InstrumentKindObservableGauge, InstrumentKindGauge:
return AggregationLastValue{}

View File

@@ -287,7 +287,14 @@ func benchReaderCollectFunc(r Reader) func(*testing.B) {
for n := 0; n < b.N; n++ {
err = r.Collect(ctx, &collectedMetrics)
assert.Equalf(b, testResourceMetricsA, collectedMetrics, "unexpected Collect response: (%#v, %v)", collectedMetrics, err)
assert.Equalf(
b,
testResourceMetricsA,
collectedMetrics,
"unexpected Collect response: (%#v, %v)",
collectedMetrics,
err,
)
}
}
}

View File

@@ -69,11 +69,26 @@ func TestGetFirstAvailableFile(t *testing.T) {
}{
{"Gets first, skip second candidate", []string{filename1, filename2}, filename1, ""},
{"Skips first, gets second candidate", []string{"does_not_exists", filename2}, filename2, ""},
{"Skips first, gets second, ignores third candidate", []string{"does_not_exists", filename2, filename1}, filename2, ""},
{
"Skips first, gets second, ignores third candidate",
[]string{"does_not_exists", filename2, filename1},
filename2,
"",
},
{"No candidates (empty slice)", []string{}, "", "no candidate file available: []"},
{"No candidates (nil slice)", nil, "", "no candidate file available: []"},
{"Single nonexisting candidate", []string{"does_not_exists"}, "", "no candidate file available: [does_not_exists]"},
{"Multiple nonexisting candidates", []string{"does_not_exists", "this_either"}, "", "no candidate file available: [does_not_exists this_either]"},
{
"Single nonexisting candidate",
[]string{"does_not_exists"},
"",
"no candidate file available: [does_not_exists]",
},
{
"Multiple nonexisting candidates",
[]string{"does_not_exists", "this_either"},
"",
"no candidate file available: [does_not_exists this_either]",
},
}
for _, tc := range tt {

View File

@@ -29,7 +29,10 @@ func TestDefaultExperimental(t *testing.T) {
serviceInstanceID, ok := res.Set().Value(semconv.ServiceInstanceIDKey)
require.True(t, ok)
matched, err := regexp.MatchString("^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$", serviceInstanceID.AsString())
matched, err := regexp.MatchString(
"^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$",
serviceInstanceID.AsString(),
)
require.NoError(t, err)
require.True(t, matched)
}

View File

@@ -409,7 +409,11 @@ func TestNew(t *testing.T) {
options: []resource.Option{
resource.WithDetectors(
resource.StringDetector("https://opentelemetry.io/schemas/1.0.0", semconv.HostNameKey, os.Hostname),
resource.StringDetector("https://opentelemetry.io/schemas/1.1.0", semconv.HostNameKey, func() (string, error) { return "", errors.New("fail") }),
resource.StringDetector(
"https://opentelemetry.io/schemas/1.1.0",
semconv.HostNameKey,
func() (string, error) { return "", errors.New("fail") },
),
),
resource.WithSchemaURL("https://opentelemetry.io/schemas/1.2.0"),
},

View File

@@ -169,7 +169,17 @@ func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.T
// slowing down all tracing consumers.
// - Logging code may be instrumented with tracing and deadlock because it could try
// acquiring the same non-reentrant mutex.
global.Info("Tracer created", "name", name, "version", is.Version, "schemaURL", is.SchemaURL, "attributes", is.Attributes)
global.Info(
"Tracer created",
"name",
name,
"version",
is.Version,
"schemaURL",
is.SchemaURL,
"attributes",
is.Attributes,
)
}
return t
}

View File

@@ -374,12 +374,26 @@ func testStoredError(t *testing.T, target interface{}) {
func TestTracerProviderReturnsSameTracer(t *testing.T) {
p := NewTracerProvider()
t0, t1, t2 := p.Tracer("t0"), p.Tracer("t1"), p.Tracer("t0", trace.WithInstrumentationAttributes(attribute.String("foo", "bar")))
t0, t1, t2 := p.Tracer(
"t0",
), p.Tracer(
"t1",
), p.Tracer(
"t0",
trace.WithInstrumentationAttributes(attribute.String("foo", "bar")),
)
assert.NotSame(t, t0, t1)
assert.NotSame(t, t0, t2)
assert.NotSame(t, t1, t2)
t3, t4, t5 := p.Tracer("t0"), p.Tracer("t1"), p.Tracer("t0", trace.WithInstrumentationAttributes(attribute.String("foo", "bar")))
t3, t4, t5 := p.Tracer(
"t0",
), p.Tracer(
"t1",
), p.Tracer(
"t0",
trace.WithInstrumentationAttributes(attribute.String("foo", "bar")),
)
assert.Same(t, t0, t3)
assert.Same(t, t1, t4)
assert.Same(t, t2, t5)

View File

@@ -151,7 +151,10 @@ func (ts *testSampler) ShouldSample(p SamplingParameters) SamplingResult {
if strings.HasPrefix(p.Name, ts.prefix) {
decision = RecordAndSample
}
return SamplingResult{Decision: decision, Attributes: []attribute.KeyValue{attribute.Int("callCount", ts.callCount)}}
return SamplingResult{
Decision: decision,
Attributes: []attribute.KeyValue{attribute.Int("callCount", ts.callCount)},
}
}
func (ts testSampler) Description() string {
@@ -374,13 +377,21 @@ func TestStartSpanNewRootNotSampled(t *testing.T) {
_, s2 := neverSampledTr.Start(ctx, "span2-no-newroot")
if !s2.SpanContext().IsSampled() {
t.Error(fmt.Errorf("got child span is not sampled, want child span with sampler: ParentBased(NeverSample()) to be sampled"))
t.Error(
fmt.Errorf(
"got child span is not sampled, want child span with sampler: ParentBased(NeverSample()) to be sampled",
),
)
}
// Adding WithNewRoot causes child spans to not sample based on parent context
_, s3 := neverSampledTr.Start(ctx, "span3-newroot", trace.WithNewRoot())
if s3.SpanContext().IsSampled() {
t.Error(fmt.Errorf("got child span is sampled, want child span WithNewRoot() and with sampler: ParentBased(NeverSample()) to not be sampled"))
t.Error(
fmt.Errorf(
"got child span is sampled, want child span WithNewRoot() and with sampler: ParentBased(NeverSample()) to not be sampled",
),
)
}
}
@@ -731,8 +742,12 @@ func TestLinks(t *testing.T) {
k2v2 := attribute.String("key2", "value2")
k3v3 := attribute.String("key3", "value3")
sc1 := trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}})
sc2 := trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}})
sc1 := trace.NewSpanContext(
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}},
)
sc2 := trace.NewSpanContext(
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}},
)
l1 := trace.Link{SpanContext: sc1, Attributes: []attribute.KeyValue{k1v1}}
l2 := trace.Link{SpanContext: sc2, Attributes: []attribute.KeyValue{k2v2, k3v3}}
@@ -773,9 +788,15 @@ func TestLinks(t *testing.T) {
func TestLinksOverLimit(t *testing.T) {
te := NewTestExporter()
sc1 := trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}})
sc2 := trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}})
sc3 := trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}})
sc1 := trace.NewSpanContext(
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}},
)
sc2 := trace.NewSpanContext(
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}},
)
sc3 := trace.NewSpanContext(
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}},
)
sl := NewSpanLimits()
sl.LinkCountLimit = 2
@@ -951,7 +972,12 @@ func startNamedSpan(tp *TracerProvider, trName, name string, args ...trace.SpanS
// passed name and with the passed context. The context is returned
// along with the span so this parent can be used to create child
// spans.
func startLocalSpan(ctx context.Context, tp *TracerProvider, trName, name string, args ...trace.SpanStartOption) (context.Context, trace.Span) {
func startLocalSpan(
ctx context.Context,
tp *TracerProvider,
trName, name string,
args ...trace.SpanStartOption,
) (context.Context, trace.Span) {
ctx, span := tp.Tracer(trName).Start(
ctx,
name,
@@ -1299,8 +1325,21 @@ func TestRecordErrorWithStackTrace(t *testing.T) {
assert.Equal(t, got.events[0].Attributes[1].Value.AsString(), want.events[0].Attributes[1].Value.AsString())
gotStackTraceFunctionName := strings.Split(got.events[0].Attributes[2].Value.AsString(), "\n")
assert.Truef(t, strings.HasPrefix(gotStackTraceFunctionName[1], "go.opentelemetry.io/otel/sdk/trace.recordStackTrace"), "%q not prefixed with go.opentelemetry.io/otel/sdk/trace.recordStackTrace", gotStackTraceFunctionName[1])
assert.Truef(t, strings.HasPrefix(gotStackTraceFunctionName[3], "go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).RecordError"), "%q not prefixed with go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).RecordError", gotStackTraceFunctionName[3])
assert.Truef(
t,
strings.HasPrefix(gotStackTraceFunctionName[1], "go.opentelemetry.io/otel/sdk/trace.recordStackTrace"),
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.recordStackTrace",
gotStackTraceFunctionName[1],
)
assert.Truef(
t,
strings.HasPrefix(
gotStackTraceFunctionName[3],
"go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).RecordError",
),
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).RecordError",
gotStackTraceFunctionName[3],
)
}
func TestRecordErrorNil(t *testing.T) {
@@ -1346,7 +1385,11 @@ func TestWithSpanKind(t *testing.T) {
}
if spanData.SpanKind() != trace.SpanKindInternal {
t.Errorf("Default value of Spankind should be Internal: got %+v, want %+v\n", spanData.SpanKind(), trace.SpanKindInternal)
t.Errorf(
"Default value of Spankind should be Internal: got %+v, want %+v\n",
spanData.SpanKind(),
trace.SpanKindInternal,
)
}
sks := []trace.SpanKind{
@@ -1397,9 +1440,15 @@ func TestWithResource(t *testing.T) {
want: resource.Default(),
},
{
name: "explicit resource",
options: []TracerProviderOption{WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)))},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
name: "explicit resource",
options: []TracerProviderOption{
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5))),
},
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk2", 5)),
),
},
{
name: "last resource wins",
@@ -1407,12 +1456,22 @@ func TestWithResource(t *testing.T) {
WithResource(resource.NewSchemaless(attribute.String("rk1", "vk1"), attribute.Int64("rk2", 5))),
WithResource(resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10))),
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk3", "rv3"), attribute.Int64("rk4", 10)),
),
},
{
name: "overlapping attributes with environment resource",
options: []TracerProviderOption{WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)))},
want: mergeResource(t, resource.Environment(), resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
name: "overlapping attributes with environment resource",
options: []TracerProviderOption{
WithResource(resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10))),
},
want: mergeResource(
t,
resource.Environment(),
resource.NewSchemaless(attribute.String("rk1", "rv1"), attribute.Int64("rk5", 10)),
),
},
}
for _, tc := range cases {
@@ -1527,8 +1586,18 @@ func TestSpanCapturesPanicWithStackTrace(t *testing.T) {
assert.Equal(t, "error message", spans[0].Events()[0].Attributes[1].Value.AsString())
gotStackTraceFunctionName := strings.Split(spans[0].Events()[0].Attributes[2].Value.AsString(), "\n")
assert.Truef(t, strings.HasPrefix(gotStackTraceFunctionName[1], "go.opentelemetry.io/otel/sdk/trace.recordStackTrace"), "%q not prefixed with go.opentelemetry.io/otel/sdk/trace.recordStackTrace", gotStackTraceFunctionName[1])
assert.Truef(t, strings.HasPrefix(gotStackTraceFunctionName[3], "go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End"), "%q not prefixed with go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End", gotStackTraceFunctionName[3])
assert.Truef(
t,
strings.HasPrefix(gotStackTraceFunctionName[1], "go.opentelemetry.io/otel/sdk/trace.recordStackTrace"),
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.recordStackTrace",
gotStackTraceFunctionName[1],
)
assert.Truef(
t,
strings.HasPrefix(gotStackTraceFunctionName[3], "go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End"),
"%q not prefixed with go.opentelemetry.io/otel/sdk/trace.(*recordingSpan).End",
gotStackTraceFunctionName[3],
)
}
func TestReadOnlySpan(t *testing.T) {
@@ -1930,7 +1999,9 @@ func TestSpanAddLink(t *testing.T) {
name: "AddLinkWithInvalidSpanContext",
attrLinkCountLimit: 128,
link: trace.Link{
SpanContext: trace.NewSpanContext(trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{}), SpanID: [8]byte{}}),
SpanContext: trace.NewSpanContext(
trace.SpanContextConfig{TraceID: trace.TraceID([16]byte{}), SpanID: [8]byte{}},
),
},
want: &snapshot{
name: "span0",

View File

@@ -26,7 +26,11 @@ var _ trace.Tracer = &tracer{}
// The Span is created with the provided name and as a child of any existing
// span context found in the passed context. The created Span will be
// configured appropriately by any SpanOption passed.
func (tr *tracer) Start(ctx context.Context, name string, options ...trace.SpanStartOption) (context.Context, trace.Span) {
func (tr *tracer) Start(
ctx context.Context,
name string,
options ...trace.SpanStartOption,
) (context.Context, trace.Span) {
config := trace.NewSpanStartConfig(options...)
if ctx == nil {
@@ -112,7 +116,12 @@ func (tr *tracer) newSpan(ctx context.Context, name string, config *trace.SpanCo
}
// newRecordingSpan returns a new configured recordingSpan.
func (tr *tracer) newRecordingSpan(psc, sc trace.SpanContext, name string, sr SamplingResult, config *trace.SpanConfig) *recordingSpan {
func (tr *tracer) newRecordingSpan(
psc, sc trace.SpanContext,
name string,
sr SamplingResult,
config *trace.SpanConfig,
) *recordingSpan {
startTime := config.Timestamp()
if startTime.IsZero() {
startTime = time.Now()