openmetrics.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Module providing support for displaying data in OpenMetrics format"""
  3. class OpenMetricsFamily: # pylint: disable=too-few-public-methods
  4. """A family of metrics.
  5. The key parameter is the metric name that should be used (snake case).
  6. The type_hint parameter must be one of 'counter', 'gauge', 'histogram', 'summary'.
  7. The help_hint parameter is a short string explaining the metric.
  8. The data_info parameter is a dictionary of descriptionary parameters for the data point (e.g. request method/path).
  9. The data parameter is a flat list of the actual data in shape of a primive type.
  10. See https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md for more information.
  11. """
  12. def __init__(self, key: str, type_hint: str, help_hint: str, data_info: list, data: list):
  13. self.key = key
  14. self.type_hint = type_hint
  15. self.help_hint = help_hint
  16. self.data_info = data_info
  17. self.data = data
  18. def __str__(self):
  19. text_representation = f"""# HELP {self.key} {self.help_hint}
  20. # TYPE {self.key} {self.type_hint}
  21. """
  22. for i, data_info_dict in enumerate(self.data_info):
  23. if not data_info_dict or not self.data[i]:
  24. continue
  25. info_representation = ','.join([f"{key}=\"{value}\"" for (key, value) in data_info_dict.items()])
  26. text_representation += f"{self.key}{{{info_representation}}} {self.data[i]}\n"
  27. return text_representation