feat(metricsserver): add Gatherer method

Add explicit Gatherer() method to improve API discoverability
and prevent users from accidentally using prometheus.DefaultGatherer
instead of the custom registry.

Changes:
- Add Gatherer() method returning prometheus.Gatherer interface
- Add NewWithDefaultGatherer() constructor for opt-in default usage
- Update package docs with usage examples
- Add tests for both gatherer modes
This commit is contained in:
2025-10-12 16:13:19 -07:00
parent 2670d25b52
commit 7291f00f48
2 changed files with 134 additions and 2 deletions

View File

@@ -67,6 +67,47 @@ func TestRegistry(t *testing.T) {
}
}
func TestGatherer(t *testing.T) {
metrics := New()
gatherer := metrics.Gatherer()
if gatherer == nil {
t.Fatal("Gatherer() returned nil")
}
// Register a test metric
counter := prometheus.NewCounter(prometheus.CounterOpts{
Name: "test_gatherer_counter",
Help: "A test counter for gatherer",
})
metrics.Registry().MustRegister(counter)
counter.Inc()
// Test that the gatherer collects our custom metric
metricFamilies, err := gatherer.Gather()
if err != nil {
t.Errorf("failed to gather metrics: %v", err)
}
found := false
for _, mf := range metricFamilies {
if mf.GetName() == "test_gatherer_counter" {
found = true
break
}
}
if !found {
t.Error("registered metric not found via Gatherer()")
}
// Verify gatherer is the same as registry
if gatherer != metrics.r {
t.Error("Gatherer() should return the same object as the registry for custom registry mode")
}
}
func TestHandler(t *testing.T) {
metrics := New()
@@ -212,6 +253,45 @@ func TestListenAndServeContextCancellation(t *testing.T) {
}
}
func TestNewWithDefaultGatherer(t *testing.T) {
metrics := NewWithDefaultGatherer()
if metrics == nil {
t.Fatal("NewWithDefaultGatherer returned nil")
}
if !metrics.useDefaultGatherer {
t.Error("useDefaultGatherer should be true")
}
gatherer := metrics.Gatherer()
if gatherer == nil {
t.Fatal("Gatherer() returned nil")
}
// Verify it returns the default gatherer
if gatherer != prometheus.DefaultGatherer {
t.Error("Gatherer() should return prometheus.DefaultGatherer when useDefaultGatherer is true")
}
// Verify the custom registry is still available and separate
if metrics.Registry() == nil {
t.Error("Registry() should still return a custom registry")
}
// Test that registering in custom registry doesn't affect default gatherer check
counter := prometheus.NewCounter(prometheus.CounterOpts{
Name: "test_default_gatherer_counter",
Help: "A test counter",
})
metrics.Registry().MustRegister(counter)
// The gatherer should still be the default one, not our custom registry
if metrics.Gatherer() != prometheus.DefaultGatherer {
t.Error("Gatherer() should continue to return prometheus.DefaultGatherer")
}
}
// Benchmark the metrics handler response time
func BenchmarkMetricsHandler(b *testing.B) {
metrics := New()