original_example.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // create a metrics registry
  14. // @note it's the users responsibility to keep the object alive
  15. auto registry = std::make_shared<Registry>();
  16. // add a new counter family to the registry (families combine values with the
  17. // same name, but distinct label dimensions)
  18. //
  19. // @note please follow the metric-naming best-practices:
  20. // https://prometheus.io/docs/practices/naming/
  21. auto& packet_counter = BuildCounter()
  22. .Name("observed_packets_total")
  23. .Help("Number of observed packets")
  24. .Register(*registry);
  25. // add and remember dimensional data, incrementing those is very cheap
  26. auto& tcp_rx_counter = packet_counter.Add({ {"protocol", "tcp"}, {"direction", "rx"} });
  27. auto& tcp_tx_counter = packet_counter.Add({ {"protocol", "tcp"}, {"direction", "tx"} });
  28. auto& udp_rx_counter = packet_counter.Add({ {"protocol", "udp"}, {"direction", "rx"} });
  29. auto& udp_tx_counter = packet_counter.Add({ {"protocol", "udp"}, {"direction", "tx"} });
  30. // add a counter whose dimensional data is not known at compile time
  31. // nevertheless dimensional values should only occur in low cardinality:
  32. // https://prometheus.io/docs/practices/naming/#labels
  33. auto& http_requests_counter = BuildCounter()
  34. .Name("http_requests_total")
  35. .Help("Number of HTTP requests")
  36. .Register(*registry);
  37. // ask the exposer to scrape the registry on incoming HTTP requests
  38. //exposer.RegisterCollectable(registry);
  39. for ( ;; ) {
  40. std::this_thread::sleep_for(std::chrono::seconds(1));
  41. const auto random_value = std::rand();
  42. if (random_value & 1) tcp_rx_counter.Increment();
  43. if (random_value & 2) tcp_tx_counter.Increment();
  44. if (random_value & 4) udp_rx_counter.Increment(10);
  45. if (random_value & 8) udp_tx_counter.Increment(10);
  46. const std::array<std::string, 4> methods = { "GET", "PUT", "POST", "HEAD" };
  47. auto method = methods.at(static_cast<std::size_t>(random_value) % methods.size());
  48. // dynamically calling Family<T>.Add() works but is slow and should be avoided
  49. http_requests_counter.Add({ {"method", method} }).Increment();
  50. TextSerializer text_serializer;
  51. text_serializer.Serialize(std::cout, registry->Collect());
  52. }
  53. }