use_counters_in_class_example.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. // use prometheus namespace
  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 global registry for use it from our classes
  19. static Registry globalRegistry;
  20. class MyClass {
  21. IntegerCounterFamily& counterFamily1 { IntegerCounter::Family::Build(globalRegistry,
  22. "counter_family_1", "counter for check integer functionality",
  23. {{"type","integer"}} ) };
  24. IntegerCounter& counter11{ counterFamily1.Add({{"number", "1"}}) };
  25. IntegerCounter& counter12{ counterFamily1.Add({{"number", "2"}}) };
  26. IntegerCounter& counter13{ counterFamily1.Add({{"number", "3"}}) };
  27. FloatingCounterFamily& counterFamily2 { FloatingCounter::Family::Build(globalRegistry,
  28. "counter_family_2", "counter for check floating functionality",
  29. {{"type","float"}} ) };
  30. FloatingCounter& counter21{ counterFamily2.Add({{"number", "1"}}) };
  31. FloatingCounter& counter22{ counterFamily2.Add({{"number", "2"}}) };
  32. FloatingCounter& counter23{ counterFamily2.Add({{"number", "3"}}) };
  33. public:
  34. MyClass() = default;
  35. void member_to_do_something() {
  36. const int random_value = std::rand();
  37. if (random_value & 1) counter11++;
  38. if (random_value & 2) counter12++;
  39. if (random_value & 4) counter13++;
  40. if (random_value & 8) counter21++;
  41. if (random_value & 16) counter22++;
  42. if (random_value & 32) counter23++;
  43. }
  44. };
  45. int main() {
  46. MyClass myClass;
  47. for (;; ) {
  48. std::this_thread::sleep_for(std::chrono::seconds(1));
  49. myClass.member_to_do_something();
  50. TextSerializer text_serializer;
  51. text_serializer.Serialize(std::cout, globalRegistry.Collect());
  52. }
  53. }