Skip to content

Commit

Permalink
Apply namespace when creating Prometheus metrics factory (fix for #732)
Browse files Browse the repository at this point in the history
Signed-off-by: Yuri Shkuro <ys@uber.com>
  • Loading branch information
Yuri Shkuro committed Mar 9, 2018
1 parent 5d4fed6 commit abb5901
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/metrics/builder.go
Expand Up @@ -68,7 +68,7 @@ func (b *Builder) InitFromViper(v *viper.Viper) *Builder {
// can be later added by RegisterHandler function.
func (b *Builder) CreateMetricsFactory(namespace string) (metrics.Factory, error) {
if b.Backend == "prometheus" {
metricsFactory := jprom.New()
metricsFactory := jprom.New().Namespace(namespace, nil)
b.handler = promhttp.HandlerFor(prometheus.DefaultGatherer, promhttp.HandlerOpts{DisableCompression: true})
return metricsFactory, nil
}
Expand Down
29 changes: 29 additions & 0 deletions pkg/metrics/builder_test.go
Expand Up @@ -15,9 +15,11 @@
package metrics

import (
"expvar"
"flag"
"testing"

"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -45,21 +47,44 @@ func TestAddFlags(t *testing.T) {
}

func TestBuilder(t *testing.T) {
assertPromCounter := func() {
families, err := prometheus.DefaultGatherer.Gather()
require.NoError(t, err)
for _, mf := range families {
if mf.GetName() == "foo:counter" {
return
}
}
t.FailNow()
}
assertExpVarCounter := func() {
var found expvar.KeyValue
expected := "foo.counter"
expvar.Do(func(kv expvar.KeyValue) {
if kv.Key == expected {
found = kv
}
})
assert.Equal(t, expected, found.Key)
}
testCases := []struct {
backend string
route string
err error
handler bool
assert func()
}{
{
backend: "expvar",
route: "/",
handler: true,
assert: assertExpVarCounter,
},
{
backend: "prometheus",
route: "/",
handler: true,
assert: assertPromCounter,
},
{
backend: "none",
Expand Down Expand Up @@ -87,6 +112,10 @@ func TestBuilder(t *testing.T) {
continue
}
require.NotNil(t, mf)
mf.Counter("counter", nil).Inc(1)
if testCase.assert != nil {
testCase.assert()
}
if testCase.handler {
require.NotNil(t, b.Handler())
}
Expand Down

0 comments on commit abb5901

Please sign in to comment.