diff --git a/std.go b/std.go new file mode 100644 index 0000000..89d80f6 --- /dev/null +++ b/std.go @@ -0,0 +1,55 @@ +package statsd + +import "sync" + +var std Statsd +var mu sync.Mutex + +func init() { + Unconfigure() +} + +// Configure creates a global StatsD client. +// TODO: Use a buffered client instead! +func Configure(host string, prefix string) error { + mu.Lock() + defer mu.Unlock() + + client := NewStatsdClient(host, prefix) + err := client.CreateSocket() + if err != nil { + return err + } + + std = client + return nil +} + +// Unconfigure resets the global StatsD client to its default state, which is +// to silently drop all events. +func Unconfigure() { + std = &NoopClient{} +} + +// These functions write to the global StatsD client if one has been configured, +// otherwise do nothing. + +func Incr(stat string, count int64) error { + return std.Incr(stat, count) +} + +func Decr(stat string, count int64) error { + return std.Decr(stat, count) +} + +func Timing(stat string, delta int64) error { + return std.Timing(stat, delta) +} + +func Absolute(stat string, value int64) error { + return std.Absolute(stat, value) +} + +func Total(stat string, value int64) error { + return std.Total(stat, value) +} diff --git a/std_test.go b/std_test.go new file mode 100644 index 0000000..54e7c73 --- /dev/null +++ b/std_test.go @@ -0,0 +1,29 @@ +package statsd + +import ( + "testing" +) + +func TestConfigure(t *testing.T) { + + // assert that global is a noop client + _, ok := std.(*NoopClient) + if !ok { + t.Errorf("expected std to be a NoopClient, got a %#v", std) + } + + // assert that after calling Configure, the global is a StatsdClient + Configure("localhost:8888", "prefix") + _, ok = std.(*StatsdClient) + if !ok { + t.Errorf("expected std to be a StatsdClient, got a %#v", std) + } + + // assert that after calling Unconfigure, the global is back to being a + // NoopClient + Unconfigure() + _, ok = std.(*NoopClient) + if !ok { + t.Errorf("expected std to be a NoopClient, got a %#v", std) + } +}