From c0221f09a30f65e4bcb049adf15d15bc606f7f90 Mon Sep 17 00:00:00 2001 From: Jonathan Prates Date: Fri, 4 May 2018 22:05:31 -0300 Subject: [PATCH] feat: lock map while writing --- metrics.go | 6 +++++- reporter.go | 6 +----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/metrics.go b/metrics.go index 6ae6509..5ce3872 100644 --- a/metrics.go +++ b/metrics.go @@ -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 @@ -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") } @@ -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 } diff --git a/reporter.go b/reporter.go index 2f4b8d5..c9bf709 100644 --- a/reporter.go +++ b/reporter.go @@ -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, @@ -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() @@ -128,6 +125,5 @@ func (r *Reporter) FlushOnce() error { }) r.Conn.Write(m.ToJSON()) m.Clear() - return nil }