histogram.h 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #pragma once
  2. #include <vector>
  3. #include <cassert>
  4. #include <algorithm>
  5. #include "prometheus/metric.h"
  6. #include "prometheus/family.h"
  7. #include "prometheus/counter.h"
  8. namespace prometheus {
  9. /// \brief A histogram metric to represent aggregatable distributions of events.
  10. ///
  11. /// This class represents the metric type histogram:
  12. /// https://prometheus.io/docs/concepts/metric_types/#histogram
  13. ///
  14. /// A histogram tracks the number of observations and the sum of the observed
  15. /// values, allowing to calculate the average of the observed values.
  16. ///
  17. /// At its core a histogram has a counter per bucket. The sum of observations
  18. /// also behaves like a counter as long as there are no negative observations.
  19. ///
  20. /// See https://prometheus.io/docs/practices/histograms/ for detailed
  21. /// explanations of histogram usage and differences to summaries.
  22. ///
  23. /// The class is thread-safe. No concurrent call to any API of this type causes
  24. /// a data race.
  25. template <typename Value_ = uint64_t>
  26. class Histogram : public Metric {
  27. using BucketBoundaries = std::vector<Value_>;
  28. const BucketBoundaries bucket_boundaries_;
  29. std::vector<Counter<Value_>> bucket_counts_;
  30. Gauge<Value_> sum_;
  31. public:
  32. using Value = Value_;
  33. using Family = CustomFamily<Histogram<Value>>;
  34. static const Metric::Type static_type = Metric::Type::Histogram;
  35. /// \brief Create a histogram with manually chosen buckets.
  36. ///
  37. /// The BucketBoundaries are a list of monotonically increasing values
  38. /// representing the bucket boundaries. Each consecutive pair of values is
  39. /// interpreted as a half-open interval [b_n, b_n+1) which defines one bucket.
  40. ///
  41. /// There is no limitation on how the buckets are divided, i.e, equal size,
  42. /// exponential etc..
  43. ///
  44. /// The bucket boundaries cannot be changed once the histogram is created.
  45. Histogram (const BucketBoundaries& buckets)
  46. : Metric(static_type), bucket_boundaries_{ buckets }, bucket_counts_{ buckets.size() + 1 }, sum_{} {
  47. assert(std::is_sorted(std::begin(bucket_boundaries_),
  48. std::end(bucket_boundaries_)));
  49. }
  50. /// \brief Observe the given amount.
  51. ///
  52. /// The given amount selects the 'observed' bucket. The observed bucket is
  53. /// chosen for which the given amount falls into the half-open interval [b_n,
  54. /// b_n+1). The counter of the observed bucket is incremented. Also the total
  55. /// sum of all observations is incremented.
  56. void Observe(const Value value) {
  57. // TODO: determine bucket list size at which binary search would be faster
  58. const auto bucket_index = static_cast<std::size_t>(std::distance(
  59. bucket_boundaries_.begin(),
  60. std::find_if(
  61. std::begin(bucket_boundaries_), std::end(bucket_boundaries_),
  62. [value](const double boundary) { return boundary >= value; })));
  63. sum_.Increment(value);
  64. bucket_counts_[bucket_index].Increment();
  65. }
  66. /// \brief Observe multiple data points.
  67. ///
  68. /// Increments counters given a count for each bucket. (i.e. the caller of
  69. /// this function must have already sorted the values into buckets).
  70. /// Also increments the total sum of all observations by the given value.
  71. void ObserveMultiple(const std::vector<Value>& bucket_increments,
  72. const Value sum_of_values) {
  73. if (bucket_increments.size() != bucket_counts_.size()) {
  74. throw std::length_error(
  75. "The size of bucket_increments was not equal to"
  76. "the number of buckets in the histogram.");
  77. }
  78. sum_.Increment(sum_of_values);
  79. for (std::size_t i{ 0 }; i < bucket_counts_.size(); ++i) {
  80. bucket_counts_[i].Increment(bucket_increments[i]);
  81. }
  82. }
  83. /// \brief Get the current value of the counter.
  84. ///
  85. /// Collect is called by the Registry when collecting metrics.
  86. virtual ClientMetric Collect() const {
  87. auto metric = ClientMetric{};
  88. auto cumulative_count = 0ULL;
  89. metric.histogram.bucket.reserve(bucket_counts_.size());
  90. for (std::size_t i{0}; i < bucket_counts_.size(); ++i) {
  91. cumulative_count += static_cast<std::size_t>(bucket_counts_[i].Get());
  92. auto bucket = ClientMetric::Bucket{};
  93. bucket.cumulative_count = cumulative_count;
  94. bucket.upper_bound = (i == bucket_boundaries_.size()
  95. ? std::numeric_limits<double>::infinity()
  96. : bucket_boundaries_[i]);
  97. metric.histogram.bucket.push_back(std::move(bucket));
  98. }
  99. metric.histogram.sample_count = cumulative_count;
  100. metric.histogram.sample_sum = sum_.Get();
  101. return metric;
  102. }
  103. };
  104. /// \brief Return a builder to configure and register a Histogram metric.
  105. ///
  106. /// @copydetails Family<>::Family()
  107. ///
  108. /// Example usage:
  109. ///
  110. /// \code
  111. /// auto registry = std::make_shared<Registry>();
  112. /// auto& histogram_family = prometheus::BuildHistogram()
  113. /// .Name("some_name")
  114. /// .Help("Additional description.")
  115. /// .Labels({{"key", "value"}})
  116. /// .Register(*registry);
  117. ///
  118. /// ...
  119. /// \endcode
  120. ///
  121. /// \return An object of unspecified type T, i.e., an implementation detail
  122. /// except that it has the following members:
  123. ///
  124. /// - Name(const std::string&) to set the metric name,
  125. /// - Help(const std::string&) to set an additional description.
  126. /// - Label(const std::map<std::string, std::string>&) to assign a set of
  127. /// key-value pairs (= labels) to the metric.
  128. ///
  129. /// To finish the configuration of the Histogram metric register it with
  130. /// Register(Registry&).
  131. using BuildHistogram = Builder<Histogram<double>>;
  132. } // namespace prometheus