Forráskód Böngészése

ChildRegistry should filter by prefix

This commit changes the behavior of PrefixedChildRegistry
to only apply the `Each` function to registered metrics
that have the the appropriate `prefix`.

This commit contains two changes:
1: An originally failing test showing the behavior
2: A wrapper func around the passed in function
for `Each` that applies the required filter
Marc Millstone 9 éve
szülő
commit
658a96a303
2 módosított fájl, 32 hozzáadás és 2 törlés
  1. 9 1
      registry.go
  2. 23 1
      registry_test.go

+ 9 - 1
registry.go

@@ -3,6 +3,7 @@ package metrics
 import (
 	"fmt"
 	"reflect"
+	"strings"
 	"sync"
 )
 
@@ -166,7 +167,14 @@ func NewPrefixedChildRegistry(parent Registry, prefix string) Registry {
 
 // Call the given function for each registered metric.
 func (r *PrefixedRegistry) Each(fn func(string, interface{})) {
-	r.underlying.Each(fn)
+	wrappedFn := func(name string, iface interface{}) {
+		if strings.HasPrefix(name, r.prefix) {
+			fn(name, iface)
+		} else {
+			return
+		}
+	}
+	r.underlying.Each(wrappedFn)
 }
 
 // Get the metric by the given name or nil if none is registered.

+ 23 - 1
registry_test.go

@@ -156,8 +156,9 @@ func TestPrefixedRegistryGetOrRegister(t *testing.T) {
 
 func TestPrefixedRegistryRegister(t *testing.T) {
 	r := NewPrefixedRegistry("prefix.")
-
 	err := r.Register("foo", NewCounter())
+	c := NewCounter()
+	Register("bar", c)
 	if err != nil {
 		t.Fatal(err.Error())
 	}
@@ -223,3 +224,24 @@ func TestPrefixedChildRegistryGet(t *testing.T) {
 		t.Fatal(name)
 	}
 }
+
+func TestChildPrefixedRegistryRegister(t *testing.T) {
+	r := NewPrefixedChildRegistry(DefaultRegistry, "prefix.")
+	err := r.Register("foo", NewCounter())
+	c := NewCounter()
+	Register("bar", c)
+	if err != nil {
+		t.Fatal(err.Error())
+	}
+
+	i := 0
+	r.Each(func(name string, m interface{}) {
+		i++
+		if name != "prefix.foo" {
+			t.Fatal(name)
+		}
+	})
+	if i != 1 {
+		t.Fatal(i)
+	}
+}