Table of contents
Part of nurago, a collection of independent Go packages for backend services.
import "github.com/tecnickcom/nurago/pkg/metrics/statsd"
Package statsd implements github.com/tecnickcom/nurago/pkg/metrics.Client
using the StatsD protocol.
It emits counters, gauges, and timers over UDP or TCP to a StatsD daemon, which then forwards aggregated metrics to downstream systems (such as Graphite-compatible storage). Application code depends on the shared metrics interface rather than the backend-specific client.
Use New to create a client and configure it with options like WithPrefix,
WithNetwork, WithAddress, and WithFlushPeriod.
Behavior Notes
StatsD is push-only in this implementation, so Client.MetricsHandlerFunc
returns HTTP 501 (Not Implemented). Database instrumentation via
Client.InstrumentDB is currently a no-op.
This package is based on github.com/tecnickcom/statsd.
When To Use
- An existing StatsD or DogStatsD agent already collects your metrics.
- You want push-based delivery over UDP with minimal overhead in the process.
Example
// A local UDP socket stands in for the StatsD daemon so the example
// needs no external process.
var lc net.ListenConfig
conn, err := lc.ListenPacket(context.TODO(), "udp", "127.0.0.1:0")
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = conn.Close() }()
// The returned Client satisfies metrics.Client, so application code
// depends on the contract rather than on StatsD.
var client metrics.Client
client, err = statsd.New(
statsd.WithNetwork("udp"),
statsd.WithAddress(conn.LocalAddr().String()),
statsd.WithPrefix("payments."),
statsd.WithFlushPeriod(100*time.Millisecond),
)
if err != nil {
fmt.Println(err)
return
}
defer func() { _ = client.Close() }()
client.IncErrorCounter("user", "read", "404")
client.IncLogLevelCounter("error")
// StatsD is push-based and exposes no scrape payload, so the metrics
// endpoint returns 501 Not Implemented.
rec := httptest.NewRecorder()
client.MetricsHandlerFunc()(rec, httptest.NewRequestWithContext(
context.TODO(), http.MethodGet, "/metrics", nil,
))
fmt.Println(rec.Code)
// Output:
// 501
Full source is in example_statsd_test.go. More runnable examples are on pkg.go.dev.
Dependencies
Importing this package pulls 2 external modules:
github.com/julienschmidt/httproutergithub.com/tecnickcom/statsd