Skip to content

Commit

Permalink
metrics: add support for dynamic labels
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Oct 11, 2021
1 parent 78eae1b commit 55fbb9b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
12 changes: 11 additions & 1 deletion metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ func (m *M) CountAndSetMax(name string, n int64) {

// SetLabel sets the specified label to value. If value == nil the label is
// removed from the set.
//
// As a special case, if value has the concrete type
//
// func() interface{}
//
// then the value of the label is obtained by calling that function.
func (m *M) SetLabel(name string, value interface{}) {
if m != nil {
m.mu.Lock()
Expand Down Expand Up @@ -111,7 +117,11 @@ func (m *M) Snapshot(snap Snapshot) {
}
if v := snap.Label; v != nil {
for name, val := range m.label {
v[name] = val
if fn, ok := val.(func() interface{}); ok {
v[name] = fn()
} else {
v[name] = val
}
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,17 @@ func TestMetrics(t *testing.T) {
m.SetLabel("hey", nil)
wantLabel("hey", nil)

var numCalls int
m.SetLabel("dyno", func() interface{} {
numCalls++
return numCalls
})
wantLabel("dyno", 1)
wantLabel("dyno", 2)
wantLabel("dyno", 3)
m.SetLabel("dyno", nil)
wantLabel("dyno", nil)

wantLabel("quux", nil)
m.EditLabel("quux", func(v interface{}) interface{} {
return "x"
Expand Down

0 comments on commit 55fbb9b

Please sign in to comment.