Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add count/sum to SummaryStats and DurationStats. #1106

Merged
merged 1 commit into from
May 5, 2023

Conversation

pstibrany
Copy link
Contributor

@pstibrany pstibrany commented Mar 29, 2023

This PR adds Count and Sum fields into SummaryStats and DurationStats. These fields are useful when converting stats into Prometheus counters or summaries. Here is how we use them in our code:

type writerMetrics struct {
	writer *kafka.Writer

	// ignoring other metrics in this example
	batchTime, batchBytes *summary
}

func (wm *writerMetrics) updateStats() {
	ws := wm.writer.Stats()

	// ignoring other metrics in this example
	wm.batchTime.add(ws.BatchTime.Count, ws.BatchTime.Sum.Seconds()) // here we use new Count and Sum fields.
	wm.batchBytes.add(ws.BatchBytes.Count, float64(ws.BatchBytes.Sum))
}

// summary is registered into Prometheus registrerer, see newSummary below.
type summary struct {
	desc *prometheus.Desc

	mu    sync.Mutex
	count uint64
	sum   float64
}

func newSummary(name, help string, reg prometheus.Registerer) *summary {
	s := &summary{
		desc: prometheus.NewDesc(name, help, nil, nil),
	}
	if reg != nil {
		reg.MustRegister(s)
	}
	return s
}

func (s *summary) add(count int64, sum float64) {
	s.mu.Lock()
	s.count += uint64(count)
	s.sum += sum
	s.mu.Unlock()
}

func (s *summary) Describe(descs chan<- *prometheus.Desc) {
	descs <- s.desc
}

func (s *summary) Collect(metrics chan<- prometheus.Metric) {
	s.mu.Lock()
	count, sum := s.count, s.sum
	s.mu.Unlock()

	metrics <- prometheus.MustNewConstSummary(s.desc, count, sum, nil)
}

Copy link
Collaborator

@rhansen2 rhansen2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution!

@rhansen2 rhansen2 merged commit ceb95ed into segmentio:main May 5, 2023
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants