metrics.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 getOrRegisterBrokerMeter(name string, broker *Broker, r metrics.Registry) metrics.Meter {
  26. return metrics.GetOrRegisterMeter(getMetricNameForBroker(name, broker), r)
  27. }
  28. func getOrRegisterBrokerHistogram(name string, broker *Broker, r metrics.Registry) metrics.Histogram {
  29. return getOrRegisterHistogram(getMetricNameForBroker(name, broker), r)
  30. }
  31. func getMetricNameForTopic(name string, topic string) string {
  32. // Convert dot to _ since reporters like Graphite typically use dot to represent hierarchy
  33. // cf. KAFKA-1902 and KAFKA-2337
  34. return fmt.Sprintf(name+"-for-topic-%s", strings.Replace(topic, ".", "_", -1))
  35. }
  36. func getOrRegisterTopicMeter(name string, topic string, r metrics.Registry) metrics.Meter {
  37. return metrics.GetOrRegisterMeter(getMetricNameForTopic(name, topic), r)
  38. }
  39. func getOrRegisterTopicHistogram(name string, topic string, r metrics.Registry) metrics.Histogram {
  40. return getOrRegisterHistogram(getMetricNameForTopic(name, topic), r)
  41. }