11package producer
22
33import (
4+ "sync"
45 "sync/atomic"
56 "time"
67
@@ -23,14 +24,23 @@ type ProducerMetrics struct {
2324
2425type ProducerMonitor struct {
2526 metrics atomic.Value // *ProducerMetrics
27+ stopCh chan struct {}
28+ wg sync.WaitGroup
2629}
2730
2831func newProducerMonitor () * ProducerMonitor {
29- m := & ProducerMonitor {}
32+ m := & ProducerMonitor {
33+ stopCh : make (chan struct {}),
34+ }
3035 m .metrics .Store (& ProducerMetrics {})
3136 return m
3237}
3338
39+ func (m * ProducerMonitor ) Stop () {
40+ close (m .stopCh )
41+ m .wg .Wait ()
42+ }
43+
3444func (m * ProducerMonitor ) recordSuccess (sendBegin time.Time , sendEnd time.Time ) {
3545 metrics := m .metrics .Load ().(* ProducerMetrics )
3646 metrics .sendBatch .AddSample (float64 (sendEnd .Sub (sendBegin ).Microseconds ()))
@@ -72,17 +82,24 @@ func (m *ProducerMonitor) getAndResetMetrics() *ProducerMetrics {
7282}
7383
7484func (m * ProducerMonitor ) reportThread (reportInterval time.Duration , logger log.Logger ) {
85+ defer m .wg .Done ()
7586 ticker := time .NewTicker (reportInterval )
76- for range ticker .C {
77- metrics := m .getAndResetMetrics ()
78- level .Info (logger ).Log ("msg" , "report status" ,
79- "sendBatch" , metrics .sendBatch .String (),
80- "retryCount" , metrics .retryCount .Load (),
81- "createBatch" , metrics .createBatch .Load (),
82- "onSuccess" , metrics .onSuccess .String (),
83- "onFail" , metrics .onFail .String (),
84- "waitMemory" , metrics .waitMemory .String (),
85- "waitMemoryFailCount" , metrics .waitMemoryFailCount .Load (),
86- )
87+ for {
88+ select {
89+ case <- ticker .C :
90+ metrics := m .getAndResetMetrics ()
91+ level .Info (logger ).Log ("msg" , "report status" ,
92+ "sendBatch" , metrics .sendBatch .String (),
93+ "retryCount" , metrics .retryCount .Load (),
94+ "createBatch" , metrics .createBatch .Load (),
95+ "onSuccess" , metrics .onSuccess .String (),
96+ "onFail" , metrics .onFail .String (),
97+ "waitMemory" , metrics .waitMemory .String (),
98+ "waitMemoryFailCount" , metrics .waitMemoryFailCount .Load (),
99+ )
100+ case <- m .stopCh :
101+ ticker .Stop ()
102+ return
103+ }
87104 }
88105}
0 commit comments