Skip to content

Commit

Permalink
Return tagged metrics registry from metrics.FromContext call.
Browse files Browse the repository at this point in the history
  • Loading branch information
James Ross committed Nov 9, 2018
1 parent 7fae951 commit ef6b5cc
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
16 changes: 14 additions & 2 deletions metrics/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,22 @@ func WithRegistry(ctx context.Context, registry Registry) context.Context {
}

func FromContext(ctx context.Context) Registry {
if registry, ok := ctx.Value(registryKey).(Registry); ok {
registry, ok := ctx.Value(registryKey).(Registry)
if !ok {
registry = DefaultMetricsRegistry
}
rootRegistry, ok := registry.(*rootRegistry)
if !ok {
return registry
}
tagsContainer, ok := ctx.Value(tagsKey).(*tagsContainer)
if !ok {
return registry
}
return DefaultMetricsRegistry
return &childRegistry{
root: rootRegistry,
tags: tagsContainer.Tags,
}
}

// AddTags adds the provided tags to the provided context. If the provided context already has tag storage, the new tags
Expand Down
15 changes: 15 additions & 0 deletions metrics/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ func TestFromContext(t *testing.T) {
assert.Equal(t, FromContext(ctx), reg)
}

func TestFromContextWithTags(t *testing.T) {
ctx := context.Background()
reg := &rootRegistry{
registry: metrics.NewPrefixedRegistry("foo"),
}

ctx = WithRegistry(ctx, reg)
ctx = AddTags(ctx, MustNewTag("bar", "baz"))

assert.Equal(t, FromContext(ctx), &childRegistry{
root: reg,
tags: Tags{MustNewTag("bar", "baz")},
})
}

func TestDefaultFromContext(t *testing.T) {
ctx := context.Background()
assert.Equal(t, FromContext(ctx), DefaultMetricsRegistry)
Expand Down

0 comments on commit ef6b5cc

Please sign in to comment.