metrics.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package sarama
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/rcrowley/go-metrics"
  6. )
  7. // Use exponentially decaying reservoir for sampling histograms with the same defaults as the Java library:
  8. // 1028 elements, which offers a 99.9% confidence level with a 5% margin of error assuming a normal distribution,
  9. // and an alpha factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements.
  10. // See https://github.com/dropwizard/metrics/blob/v3.1.0/metrics-core/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java#L38
  11. const (
  12. metricsReservoirSize = 1028
  13. metricsAlphaFactor = 0.015
  14. )
  15. func getOrRegisterHistogram(name string, r metrics.Registry) metrics.Histogram {
  16. return r.GetOrRegister(name, func() metrics.Histogram {
  17. return metrics.NewHistogram(metrics.NewExpDecaySample(metricsReservoirSize, metricsAlphaFactor))
  18. }).(metrics.Histogram)
  19. }
  20. func getMetricNameForBroker(name string, broker *Broker) string {
  21. // Use broker id like the Java client as it does not contain '.' or ':' characters that
  22. // can be interpreted as special character by monitoring tool (e.g. Graphite)
  23. return fmt.Sprintf(name+"-for-broker-%d", broker.ID())
  24. }
  25. func getMetricNameForTopic(name string, topic string) string {
  26. // Convert dot to _ since reporters like Graphite typically use dot to represent hierarchy
  27. // cf. KAFKA-1902 and KAFKA-2337
  28. return fmt.Sprintf(name+"-for-topic-%s", strings.Replace(topic, ".", "_", -1))
  29. }
  30. func getOrRegisterTopicMeter(name string, topic string, r metrics.Registry) metrics.Meter {
  31. return metrics.GetOrRegisterMeter(getMetricNameForTopic(name, topic), r)
  32. }
  33. func getOrRegisterTopicHistogram(name string, topic string, r metrics.Registry) metrics.Histogram {
  34. return getOrRegisterHistogram(getMetricNameForTopic(name, topic), r)
  35. }