2
0

modern_example.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include <prometheus/registry.h>
  2. #include <prometheus/counter.h>
  3. #include <prometheus/text_serializer.h>
  4. #include <array>
  5. #include <chrono>
  6. #include <cstdlib>
  7. #include <memory>
  8. #include <string>
  9. #include <thread>
  10. #include <iostream>
  11. int main() {
  12. using namespace prometheus;
  13. // for clarity, we deduce the required types
  14. using IntegerCounter = Counter<uint64_t>;
  15. using FloatingCounter = Counter<double>;
  16. using IntegerCounterFamily = CustomFamily<IntegerCounter>;
  17. using FloatingCounterFamily = CustomFamily<FloatingCounter>;
  18. // create a metrics registry
  19. // @note it's the users responsibility to keep the object alive
  20. Registry registry;
  21. // add a new counter family to the registry (families combine values with the
  22. // same name, but distinct label dimensions)
  23. //
  24. // @note please follow the metric-naming best-practices:
  25. // https://prometheus.io/docs/practices/naming/
  26. FloatingCounterFamily& packet_counter{ FloatingCounter::Family::Build(registry, "observed_packets_total", "Number of observed packets") };
  27. // add and remember dimensional data, incrementing those is very cheap
  28. FloatingCounter& tcp_rx_counter{ packet_counter.Add({ {"protocol", "tcp"}, {"direction", "rx"} }) };
  29. FloatingCounter& tcp_tx_counter{ packet_counter.Add({ {"protocol", "tcp"}, {"direction", "tx"} }) };
  30. FloatingCounter& udp_rx_counter{ packet_counter.Add({ {"protocol", "udp"}, {"direction", "rx"} }) };
  31. FloatingCounter& udp_tx_counter{ packet_counter.Add({ {"protocol", "udp"}, {"direction", "tx"} }) };
  32. // add a counter whose dimensional data is not known at compile time
  33. // nevertheless dimensional values should only occur in low cardinality:
  34. // https://prometheus.io/docs/practices/naming/#labels
  35. IntegerCounterFamily& http_requests_counter = IntegerCounter::Family::Build(registry, "http_requests_total", "Number of HTTP requests");
  36. for (;; ) {
  37. std::this_thread::sleep_for(std::chrono::seconds(1));
  38. const int random_value = std::rand();
  39. if (random_value & 1) tcp_rx_counter++;
  40. if (random_value & 2) ++tcp_tx_counter;
  41. if (random_value & 4) udp_rx_counter += 0.5;
  42. if (random_value & 8) udp_tx_counter += 0.7;
  43. const std::array<std::string, 4> methods = { "GET", "PUT", "POST", "HEAD" };
  44. const std::string& method = methods.at(static_cast<std::size_t>(random_value) % methods.size());
  45. // dynamically calling Family<T>.Add() works but is slow and should be avoided
  46. http_requests_counter.Add({ {"method", method} }) += 10;
  47. TextSerializer text_serializer;
  48. text_serializer.Serialize(std::cout, registry.Collect());
  49. }
  50. }