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

Commit

Permalink
feat: lock map while writing
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathansp committed May 5, 2018
1 parent cc9088b commit c0221f0
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
6 changes: 5 additions & 1 deletion metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ package logstash
import (
"encoding/json"
"errors"
"sync"
)

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

// NewMetrics Metric{} constructor
Expand All @@ -22,6 +24,9 @@ func NewMetrics(metric string) *Metrics {
}

func (m *Metrics) register(name string, value interface{}) error {
m.RLock()
defer m.RUnlock()

if name == "" {
return errors.New("Invalid metric name")
}
Expand Down Expand Up @@ -50,6 +55,5 @@ func (m *Metrics) Clear() {
// ToJSON serializes data to json
func (m *Metrics) ToJSON() []byte {
data, _ := json.Marshal(m.data)
data = append(data, "\n"...)
return data
}
6 changes: 1 addition & 5 deletions reporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ func NewReporter(r metrics.Registry, addr string, name string) (*Reporter, error
return nil, err
}

conn.SetWriteBuffer(2048)

return &Reporter{
Conn: conn,
Registry: r,
Expand Down Expand Up @@ -67,12 +65,11 @@ func (r *Reporter) FlushEach(interval time.Duration) {
}
}

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

r.Registry.Each(func(name string, i interface{}) {

switch metric := i.(type) {
case metrics.Counter:
v := metric.Count()
Expand Down Expand Up @@ -128,6 +125,5 @@ func (r *Reporter) FlushOnce() error {
})
r.Conn.Write(m.ToJSON())
m.Clear()

return nil
}

0 comments on commit c0221f0

Please sign in to comment.