Adding a rate counter metric to go's expvar

November 30, 2015

Some days ago, I needed to expose a metric with the hits per second to a service. After a quick search in Google I hit a post from datadog.

It highlighted exactly what I was looking for: A go library called ratecounter described as “A Thread-Safe RateCounter implementation in Golang”. Bingo.

What I’ve found odd at that post was the way ratecounter was used:

var (
	counter        *ratecounter.RateCounter
	hitsperminute = expvar.NewInt("hits_per_minute")

I though RaterCounter instances should be able to handle exposing in their own. So after checking the code at github, I found the implementation was not satisfying expvar.Var interface which consist in just

type Var interface {
    String() string

After forking, adding a the required method and a pull request, now ratecounter is able to play nicely as a expvar.

The only missing thing at this point was to tell expvar package to include our instance when collecting the metrics. Init is usually a good place to place this kind of initialization

var counter = ratecounter.NewRateCounter(1 * time.Second)

func init(){
    expvar.publish("hitsPerSecond", counter)

Hope you find this useful when adding metrics to your services.

comments powered by Disqus