2
0

use_gauge_in_class_example.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <prometheus/registry.h>
  2. #include <prometheus/gauge.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 IntegerGauge = Gauge<int64_t>;
  15. using FloatingGauge = Gauge<double>;
  16. using IntegerGaugeFamily = CustomFamily<IntegerGauge>;
  17. using FloatingGaugeFamily = CustomFamily<FloatingGauge>;
  18. // create global registry for use it from our classes
  19. static Registry globalRegistry;
  20. class MyClass {
  21. IntegerGaugeFamily& gaugeFamily1 { IntegerGauge::Family::Build(globalRegistry,
  22. "gauge_family_1", "gauge for check integer functionality",
  23. {{"type","integer"}} ) };
  24. IntegerGauge& gauge11{ gaugeFamily1.Add({{"number", "1"}}) };
  25. IntegerGauge& gauge12{ gaugeFamily1.Add({{"number", "2"}}) };
  26. IntegerGauge& gauge13{ gaugeFamily1.Add({{"number", "3"}}) };
  27. FloatingGaugeFamily& gaugeFamily2 { FloatingGauge::Family::Build(globalRegistry,
  28. "gauge_family_2", "gauge for check floating functionality",
  29. {{"type","float"}} ) };
  30. FloatingGauge& gauge21{ gaugeFamily2.Add({{"number", "1"}}) };
  31. FloatingGauge& gauge22{ gaugeFamily2.Add({{"number", "2"}}) };
  32. FloatingGauge& gauge23{ gaugeFamily2.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 ) gauge11++; else gauge11--;
  38. if (random_value & (1 << 1)) gauge12++; else gauge12--;
  39. if (random_value & (1 << 2)) gauge13++; else gauge13--;
  40. if (random_value & (1 << 3)) gauge21++; else gauge21--;
  41. if (random_value & (1 << 4)) gauge22++; else gauge22--;
  42. if (random_value & (1 << 5)) gauge23++; else gauge23--;
  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. }