~mna/webparts-expvar

bb965efaf6c011b095306527c99bfe10eac58e25 — Martin Angers 3 years ago 3387e0d
implement missing metrics
2 files changed, 62 insertions(+), 2 deletions(-)

M expvar.go
M expvar_test.go
M expvar.go => expvar.go +38 -1
@@ 9,7 9,8 @@ import (
	"git.sr.ht/~mna/webparts/metric"
)

// NewCounter creates a new counter with the specified name.
// NewCounter creates a new counter with the specified name. It panics if the
// name is already used for another metric.
func NewCounter(name string) metric.Counter {
	return (*counter)(expvar.NewFloat(name))
}


@@ 26,3 27,39 @@ func (c *counter) Add(increment float64) {
	}
	(*expvar.Float)(c).Add(increment)
}

// NewGauge creates a new gauge with the specified name. It panics if the
// name is already used for another metric.
func NewGauge(name string) metric.Gauge {
	return (*gauge)(expvar.NewFloat(name))
}

type gauge expvar.Float

func (g *gauge) Inc() {
	g.Add(1)
}

func (g *gauge) Dec() {
	g.Add(-1)
}

func (g *gauge) Add(delta float64) {
	(*expvar.Float)(g).Add(delta)
}

func (g *gauge) Set(value float64) {
	(*expvar.Float)(g).Set(value)
}

// NewHistogram creates a new histogram with the specified name. It panics if the
// name is already used for another metric.
func NewHistogram(name string) metric.Histogram {
	return (*histogram)(expvar.NewFloat(name))
}

type histogram expvar.Float

func (h *histogram) Observe(value float64) {
	(*expvar.Float)(h).Set(value)
}

M expvar_test.go => expvar_test.go +24 -1
@@ 8,7 8,7 @@ import (
)

func TestCounter(t *testing.T) {
	c := NewCounter("test")
	c := NewCounter("counter")

	c.Inc()
	c.Inc()


@@ 18,3 18,26 @@ func TestCounter(t *testing.T) {
		c.Add(-1)
	})
}

func TestGauge(t *testing.T) {
	g := NewGauge("gauge")

	g.Inc()
	g.Inc()
	g.Add(3)
	g.Dec()
	g.Add(-5)
	require.Equal(t, "-1", (*expvar.Float)(g.(*gauge)).String())
	g.Set(7)
	g.Dec()
	require.Equal(t, "6", (*expvar.Float)(g.(*gauge)).String())
}

func TestHistogram(t *testing.T) {
	h := NewHistogram("histogram")

	h.Observe(1)
	h.Observe(3)
	h.Observe(-2)
	require.Equal(t, "-2", (*expvar.Float)(h.(*histogram)).String())
}