Skip to content

Commit

Permalink
metrics: Return all registered metrics
Browse files Browse the repository at this point in the history
  • Loading branch information
codebien committed May 11, 2023
1 parent c00bfbb commit 74a2e13
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
15 changes: 15 additions & 0 deletions metrics/registry.go
Expand Up @@ -71,6 +71,21 @@ func (r *Registry) MustNewMetric(name string, typ MetricType, t ...ValueType) *M
return m
}

// All returns all the registered metrics.
func (r *Registry) All() []*Metric {
r.l.RLock()
defer r.l.RUnlock()

if len(r.metrics) < 1 {
return nil
}
s := make([]*Metric, 0, len(r.metrics))
for _, m := range r.metrics {
s = append(s, m)
}
return s
}

func (r *Registry) newMetric(name string, mt MetricType, vt ...ValueType) *Metric {
valueType := Default
if len(vt) > 0 {
Expand Down
36 changes: 36 additions & 0 deletions metrics/registry_test.go
@@ -1,6 +1,7 @@
package metrics

import (
"strconv"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -65,3 +66,38 @@ func TestRegistryBranchTagSetRootWith(t *testing.T) {

assert.Equal(t, raw, tags.Map())
}

func TestRegistryAll(t *testing.T) {
t.Parallel()

t.Run("Empty", func(t *testing.T) {
t.Parallel()
r := NewRegistry()
assert.Nil(t, r.All())
})

t.Run("MultipleItems", func(t *testing.T) {
t.Parallel()
r := NewRegistry()

exp := make([]string, 5)
for i := 1; i <= 5; i++ {
name := "metric" + strconv.Itoa(i)
_, err := r.NewMetric(name, Counter)
require.NoError(t, err)

exp[i-1] = name
}
metrics := r.All()
require.Len(t, metrics, 5)

names := func(m []*Metric) []string {
s := make([]string, len(m))
for i := 0; i < len(m); i++ {
s[i] = m[i].Name
}
return s
}
assert.ElementsMatch(t, exp, names(metrics))
})
}

0 comments on commit 74a2e13

Please sign in to comment.