Skip to content

Commit

Permalink
fix: always reset all metrics before writing them when calling WriteTo
Browse files Browse the repository at this point in the history
This prevents the Dogstatsd client to consume an ever-increasing amount
of memory when it fails to write somme metrics. Without this fix, if
counters can't be written, timings and histograms are not reset.
  • Loading branch information
skwair committed Jun 2, 2022
1 parent d7cefca commit bb963bf
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions metrics/dogstatsd/dogstatsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,9 +141,14 @@ func (d *Dogstatsd) SendLoop(ctx context.Context, c <-chan time.Time, network, a
// lost if there is a problem with the write. Clients should be sure to call
// WriteTo regularly, ideally through the WriteLoop or SendLoop helper methods.
func (d *Dogstatsd) WriteTo(w io.Writer) (count int64, err error) {
var n int

d.counters.Reset().Walk(func(name string, lvs lv.LabelValues, values []float64) bool {
var (
n int
counters = d.counters.Reset()
timings = d.timings.Reset()
histograms = d.histograms.Reset()
)

counters.Walk(func(name string, lvs lv.LabelValues, values []float64) bool {
n, err = fmt.Fprintf(w, "%s%s:%f|c%s%s\n", d.prefix, name, sum(values), sampling(d.rates.Get(name)), d.tagValues(lvs))
if err != nil {
return false
Expand All @@ -168,7 +173,7 @@ func (d *Dogstatsd) WriteTo(w io.Writer) (count int64, err error) {
}
d.mtx.RUnlock()

d.timings.Reset().Walk(func(name string, lvs lv.LabelValues, values []float64) bool {
timings.Walk(func(name string, lvs lv.LabelValues, values []float64) bool {
sampleRate := d.rates.Get(name)
for _, value := range values {
n, err = fmt.Fprintf(w, "%s%s:%f|ms%s%s\n", d.prefix, name, value, sampling(sampleRate), d.tagValues(lvs))
Expand All @@ -183,7 +188,7 @@ func (d *Dogstatsd) WriteTo(w io.Writer) (count int64, err error) {
return count, err
}

d.histograms.Reset().Walk(func(name string, lvs lv.LabelValues, values []float64) bool {
histograms.Walk(func(name string, lvs lv.LabelValues, values []float64) bool {
sampleRate := d.rates.Get(name)
for _, value := range values {
n, err = fmt.Fprintf(w, "%s%s:%f|h%s%s\n", d.prefix, name, value, sampling(sampleRate), d.tagValues(lvs))
Expand Down

0 comments on commit bb963bf

Please sign in to comment.