Ver código fonte

PrefixRegistries of PrefixedRegistries

Allow the Each function to handle PrefixedRegistries
of PrefixedRegistries by first walking the set of
registries to compute the full prefix and
then applying a filter function to the base registry
Marc Millstone 9 anos atrás
pai
commit
4fb3d81c18
3 arquivos alterados com 61 adições e 7 exclusões
  1. 1 1
      exp/exp.go
  2. 20 6
      registry.go
  3. 40 0
      registry_test.go

+ 1 - 1
exp/exp.go

@@ -8,7 +8,7 @@ import (
 	"net/http"
 	"sync"
 
-	"github.com/splittingfield/go-metrics"
+	"github.com/rcrowley/go-metrics"
 )
 
 type exp struct {

+ 20 - 6
registry.go

@@ -167,14 +167,28 @@ func NewPrefixedChildRegistry(parent Registry, prefix string) Registry {
 
 // Call the given function for each registered metric.
 func (r *PrefixedRegistry) Each(fn func(string, interface{})) {
-	wrappedFn := func(name string, iface interface{}) {
-		if strings.HasPrefix(name, r.prefix) {
-			fn(name, iface)
-		} else {
-			return
+	wrappedFn := func (prefix string) func(string, interface{}) {
+		return func(name string, iface interface{}) {
+			if strings.HasPrefix(name,prefix) {
+				fn(name, iface)
+			} else {
+				return
+			}
 		}
 	}
-	r.underlying.Each(wrappedFn)
+
+	baseRegistry, prefix := walkRegistries(r, "")
+	baseRegistry.Each(wrappedFn(prefix))
+}
+
+func walkRegistries(registry Registry, prefix string) (Registry, string) {
+	switch r := registry.(type) {
+	case *PrefixedRegistry:
+		return walkRegistries(r.underlying, r.prefix + prefix)
+	case *StandardRegistry:
+		return r, prefix
+	}
+	return nil, ""
 }
 
 // Get the metric by the given name or nil if none is registered.

+ 40 - 0
registry_test.go

@@ -2,6 +2,7 @@ package metrics
 
 import (
 	"testing"
+	"github.com/stretchr/testify/assert"
 )
 
 func BenchmarkRegistry(b *testing.B) {
@@ -245,3 +246,42 @@ func TestChildPrefixedRegistryRegister(t *testing.T) {
 		t.Fatal(i)
 	}
 }
+
+func TestChildPrefixedRegistryOfChildRegister(t *testing.T) {
+	r := NewPrefixedChildRegistry(NewRegistry(), "prefix.")
+	r2 := NewPrefixedChildRegistry(r, "prefix2.")
+	err := r.Register("foo2", NewCounter())
+	if err != nil {
+		t.Fatal(err.Error())
+	}
+	err = r2.Register("baz", NewCounter())
+	c := NewCounter()
+	Register("bars", c)
+
+	i := 0
+	r2.Each(func(name string, m interface{}) {
+		i++
+		if name != "prefix.prefix2.baz" {
+			//t.Fatal(name)
+		}
+	})
+	if i != 1 {
+		t.Fatal(i)
+	}
+}
+
+func TestWalkRegistries(t *testing.T) {
+	r := NewPrefixedChildRegistry(NewRegistry(), "prefix.")
+	r2 := NewPrefixedChildRegistry(r, "prefix2.")
+	err := r.Register("foo2", NewCounter())
+	if err != nil {
+		t.Fatal(err.Error())
+	}
+	err = r2.Register("baz", NewCounter())
+	c := NewCounter()
+	Register("bars", c)
+
+	_, prefix := walkRegistries(r2, "")
+	assert.Equal(t, "prefix.prefix2.", prefix)
+
+}