From e98f683b9cfc397203296b8e26226de5465b51de Mon Sep 17 00:00:00 2001 From: brawndou <112038567+brawndou@users.noreply.github.com> Date: Fri, 16 Feb 2024 15:17:21 -0800 Subject: [PATCH] do not allocate gauge if cardinality metrics are turned off (#246) * do not allocate gauge if cardinality metrics are turned off * add test cases --- scope_registry.go | 2 +- scope_registry_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/scope_registry.go b/scope_registry.go index d1481da..fc1b50b 100644 --- a/scope_registry.go +++ b/scope_registry.go @@ -103,7 +103,7 @@ func newScopeRegistryWithShardCount( } r.subscopes[i].s[scopeRegistryKey(root.prefix, root.tags)] = root } - if r.root.cachedReporter != nil { + if r.root.cachedReporter != nil && !omitCardinalityMetrics { r.cachedCounterCardinalityGauge = r.root.cachedReporter.AllocateGauge(r.sanitizedCounterCardinalityName, r.cardinalityMetricsTags) r.cachedGaugeCardinalityGauge = r.root.cachedReporter.AllocateGauge(r.sanitizedGaugeCardinalityName, r.cardinalityMetricsTags) r.cachedHistogramCardinalityGauge = r.root.cachedReporter.AllocateGauge(r.sanitizedHistogramCardinalityName, r.cardinalityMetricsTags) diff --git a/scope_registry_test.go b/scope_registry_test.go index 5339fc2..66dc189 100644 --- a/scope_registry_test.go +++ b/scope_registry_test.go @@ -221,3 +221,39 @@ func TestForEachScopeConcurrent(t *testing.T) { <-done } + +func TestCachedReporterInternalMetricsAlloc(t *testing.T) { + tests := []struct { + name string + omitCardinalityMetrics bool + wantGauges int + }{ + { + name: "omit metrics", + omitCardinalityMetrics: true, + wantGauges: 1, + }, + { + name: "include metrics", + omitCardinalityMetrics: false, + wantGauges: 1 + numInternalMetrics, + }, + } + + for _, tt := range tests { + r := newTestStatsReporter() + root, closer := NewRootScope(ScopeOptions{CachedReporter: r, OmitCardinalityMetrics: tt.omitCardinalityMetrics}, 0) + s := root.(*scope) + + r.gg.Add(tt.wantGauges) + s.Gauge("gauge-foo").Update(3) + + closer.Close() + r.WaitAll() + + assert.Equal( + t, tt.wantGauges, len(r.gauges), "%n: expected %d gauges, got %d gauges", tt.name, tt.wantGauges, + len(r.gauges), + ) + } +}