openmetrics.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include "openmetrics.h"
  2. /**
  3. * create a singe metric from the given input
  4. **/
  5. std::string createMetric(const std::string &metricName, const std::string &help, const std::string &type, const std::string &value)
  6. {
  7. return "# HELP " + metricName + " " + help + "\n" +
  8. "# TYPE " + metricName + " " + type + "\n" +
  9. metricName + " " + value + "\n";
  10. }
  11. /**
  12. * Generate the MetricFamily from all available sequences
  13. * @returns the string containing the text wire format of the MetricFamily
  14. **/
  15. std::string createSequenceMetrics(std::string prefix, const std::vector<NumberPost *> &numbers)
  16. {
  17. std::string res;
  18. for (const auto &number : numbers)
  19. {
  20. // only valid data is reported (https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#missing-data)
  21. if (number->ReturnValue.length() > 0)
  22. {
  23. auto label = number->name;
  24. // except newline, double quote, and backslash (https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#abnf)
  25. // to keep it simple, these characters are just removed from the label
  26. replaceAll(label, "\\", "");
  27. replaceAll(label, "\"", "");
  28. replaceAll(label, "\n", "");
  29. res += prefix + "_flow_value{sequence=\"" + label + "\"} " + number->ReturnValue + "\n";
  30. }
  31. }
  32. // prepend metadata if a valid metric was created
  33. if (res.length() > 0)
  34. {
  35. res = "# HELP " + prefix + "_flow_value current value of meter readout\n# TYPE " + prefix + "_flow_value gauge\n" + res;
  36. }
  37. return res;
  38. }