Skip to content

Commit

Permalink
add gauge support and more docs
Browse files Browse the repository at this point in the history
  • Loading branch information
cyberdelia committed Jul 18, 2012
1 parent 3597477 commit b41de02
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
17 changes: 14 additions & 3 deletions statsd.go
Expand Up @@ -10,6 +10,7 @@ import (
"time"
)

// A statsd client representing a connection to a statsd server.
type Client struct {
Name string
rw *bufio.ReadWriter
Expand All @@ -19,6 +20,7 @@ func millisecond(d time.Duration) int {
return int(d.Seconds() * 1000)
}

// Dial connects to the given address on the given network using net.Dial and then returns a new Client for the connection.
func Dial(addr string) (*Client, error) {
rw, err := net.Dial("udp", addr)
if err != nil {
Expand All @@ -34,26 +36,35 @@ func newClient(name string, rw io.ReadWriter) *Client {
return c
}

// Increment the counter for the given bucket
func (c *Client) Increment(stat string, count int, rate float64) error {
return c.Send(stat, rate, "%d|c", count)
return c.send(stat, rate, "%d|c", count)
}

// Decrement the counter for the given bucket
func (c *Client) Decrement(stat string, count int, rate float64) error {
return c.Increment(stat, -count, rate)
}

// Record time spend for the given bucket
func (c *Client) Timing(stat string, delta int, rate float64) error {
return c.Send(stat, rate, "%d|ms", delta)
return c.send(stat, rate, "%d|ms", delta)
}

// Calculate time spend in given function and send it
func (c *Client) Time(stat string, rate float64, f func()) error {
ts := time.Now()
f()
delta := millisecond(time.Now().Sub(ts))
return c.Timing(stat, delta, rate)
}

func (c *Client) Send(stat string, rate float64, format string, args ...interface{}) error {
// Record arbitrary values for the given bucket
func (c *Client) Gauge(stat string, value int, rate float64) error {
return c.send(stat, rate, "%d|g", value)
}

func (c *Client) send(stat string, rate float64, format string, args ...interface{}) error {
if rate < 1 {
if rand.Float64() < rate {
format = fmt.Sprintf("%s|@%1.2f", format, rate)
Expand Down
8 changes: 8 additions & 0 deletions statsd_test.go
Expand Up @@ -48,6 +48,14 @@ func TestIncrementRate(t *testing.T) {
assert.Equal(t, data, "incr:1|c|@0.99")
}

func TestGauge(t *testing.T) {
c := newClient("<fake>", fake())
err := c.Gauge("gauge", 300, 1)
assert.Equal(t, err, nil)
data := readData(c.rw)
assert.Equal(t, data, "gauge:300|g")
}

func TestMilliseconds(t *testing.T) {
msec, _ := time.ParseDuration("350ms")
assert.Equal(t, 350, millisecond(msec))
Expand Down

0 comments on commit b41de02

Please sign in to comment.