XStats
Package xstats
is a generic client for service instrumentation.
xstats
is inspired from Go-kit's metrics package but it takes a slightly different path. Instead of having to create an instance for each metric, xstats
use a single instance to log every metrics you want. This reduces the boiler plate when you have a lot a metrics in your app. It's also easier in term of dependency injection.
Talking about dependency injection, xstats
comes with a xhandler.Handler integration so it can automatically inject the xstats
client within the net/context
of each request. Each request's xstats
instance have its own tags storage ; This let you inject some per request contextual tags to be included with all observations sent within the lifespan of the request.
xstats
is pluggable and comes with integration for expvar
, StatsD
and DogStatsD
, the Datadog augmented version of StatsD with support for tags. More integration may come later (PR welcome).
Supported Clients
Install
go get github.com/rs/xstats
Usage
flushInterval := 5 * time.Second
statsdWriter, err := net.Dial("udp", "127.0.0.1:8126")
if err != nil {
log.Fatal(err)
}
s := xstats.New(dogstatsd.New(statsdWriter, flushInterval))
s.AddTags("role:my-service", "dc:sv6")
s.Count("requests", 1, "tag")
s.Timing("something", 5*time.Millisecond, "tag")
Integration with github.com/rs/xhandler:
var xh xhandler.HandlerC
xh = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := xstats.FromRequest(r)
m.Count("requests", 1, "route:index")
})
flushInterval := 5 * time.Second
tags := []string{"role:my-service"}
statsdWriter, err := net.Dial("udp", "127.0.0.1:8126")
if err != nil {
log.Fatal(err)
}
xh = xstats.NewHandler(dogstatsd.New(statsdWriter, flushInterval), tags, xh)
ctx := context.Background()
h := xhandler.New(ctx, xh)
http.Handle("/", h)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
Testing
func TestFunc(t *testing.T) {
m := mock.New()
s := xstats.New(m)
m.On("Timing", "something", 5*time.Millisecond, "tag")
s.Timing("something", 5*time.Millisecond, "tag")
s.AssertExpectations(t)
}
Licenses
All source code is licensed under the MIT License.