Skip to content
This repository has been archived by the owner on Aug 19, 2024. It is now read-only.

Commit

Permalink
feat: add Clear() method
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathansp committed May 4, 2018
1 parent 3e6b91c commit cc9088b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
11 changes: 9 additions & 2 deletions metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import (

// Metrics represents a metric that will be sent to logstash
type Metrics struct {
data map[string]interface{}
data map[string]interface{}
metric string
}

// NewMetrics Metric{} constructor
Expand All @@ -31,13 +32,19 @@ func (m *Metrics) register(name string, value interface{}) error {
// Gauge register a new gauge metric
func (m *Metrics) Gauge(name string, value interface{}) error {
return m.register(name+".gauge", value)

}

// Count register a new gaugeFloat64 metric
func (m *Metrics) Count(name string, value int64) error {
return m.register(name, value)
}

// Clear clears current buffer
func (m *Metrics) Clear() {
m.data = map[string]interface{}{
"metric": m.metric,
"count": 1,
}
}

// ToJSON serializes data to json
Expand Down
20 changes: 14 additions & 6 deletions reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ type Reporter struct {
// Registry map is used to hold metrics that will be sent to logstash.
Registry metrics.Registry
// Conn is a UDP connection to logstash.
Conn net.Conn
Conn *net.UDPConn
// Name of this reporter
Name string

// Reporter type configuration settings
percentiles []float64
p []string
ss map[string]int64
udpAddr *net.UDPAddr
}

// NewReporter creates a new Reporter with a pre-configured statsd client.
Expand All @@ -29,16 +29,23 @@ func NewReporter(r metrics.Registry, addr string, name string) (*Reporter, error
r = metrics.DefaultRegistry
}

conn, err := net.Dial("udp", addr)
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return nil, err
}
conn, err := net.DialUDP("udp4", nil, udpAddr)
if err != nil {
return nil, err
}

conn.SetWriteBuffer(2048)

return &Reporter{
Conn: conn,
Registry: r,
Name: name,

udpAddr: udpAddr,
percentiles: []float64{0.50, 0.75, 0.95, 0.99, 0.999},
ss: make(map[string]int64),
}, nil
Expand All @@ -62,8 +69,9 @@ func (r *Reporter) FlushEach(interval time.Duration) {

// FlushOnce submits a snapshot submission of the registry.
func (r *Reporter) FlushOnce() error {
m := NewMetrics(r.Name)

r.Registry.Each(func(name string, i interface{}) {
m := NewMetrics(r.Name)

switch metric := i.(type) {
case metrics.Counter:
Expand Down Expand Up @@ -116,10 +124,10 @@ func (r *Reporter) FlushOnce() error {
m.Gauge(name+p, time.Duration(values[i]).Seconds()*1000)
}
}

}
r.Conn.Write(m.ToJSON())
})
r.Conn.Write(m.ToJSON())
m.Clear()

return nil
}

0 comments on commit cc9088b

Please sign in to comment.