exposition.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/python
  2. from __future__ import unicode_literals
  3. from ..utils import floatToGoString
  4. CONTENT_TYPE_LATEST = str('application/openmetrics-text; version=0.0.1; charset=utf-8')
  5. """Content type of the latest OpenMetrics text format"""
  6. def generate_latest(registry):
  7. '''Returns the metrics from the registry in latest text format as a string.'''
  8. output = []
  9. for metric in registry.collect():
  10. try:
  11. mname = metric.name
  12. output.append('# HELP {0} {1}\n'.format(
  13. mname, metric.documentation.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"')))
  14. output.append('# TYPE {0} {1}\n'.format(mname, metric.type))
  15. if metric.unit:
  16. output.append('# UNIT {0} {1}\n'.format(mname, metric.unit))
  17. for s in metric.samples:
  18. if s.labels:
  19. labelstr = '{{{0}}}'.format(','.join(
  20. ['{0}="{1}"'.format(
  21. k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
  22. for k, v in sorted(s.labels.items())]))
  23. else:
  24. labelstr = ''
  25. if s.exemplar:
  26. if metric.type not in ('histogram', 'gaugehistogram') or not s.name.endswith('_bucket'):
  27. raise ValueError("Metric {0} has exemplars, but is not a histogram bucket".format(metric.name))
  28. labels = '{{{0}}}'.format(','.join(
  29. ['{0}="{1}"'.format(
  30. k, v.replace('\\', r'\\').replace('\n', r'\n').replace('"', r'\"'))
  31. for k, v in sorted(s.exemplar.labels.items())]))
  32. if s.exemplar.timestamp is not None:
  33. exemplarstr = ' # {0} {1} {2}'.format(
  34. labels,
  35. floatToGoString(s.exemplar.value),
  36. s.exemplar.timestamp,
  37. )
  38. else:
  39. exemplarstr = ' # {0} {1}'.format(
  40. labels,
  41. floatToGoString(s.exemplar.value),
  42. )
  43. else:
  44. exemplarstr = ''
  45. timestamp = ''
  46. if s.timestamp is not None:
  47. timestamp = ' {0}'.format(s.timestamp)
  48. output.append('{0}{1} {2}{3}{4}\n'.format(
  49. s.name,
  50. labelstr,
  51. floatToGoString(s.value),
  52. timestamp,
  53. exemplarstr,
  54. ))
  55. except Exception as exception:
  56. exception.args = (exception.args or ('',)) + (metric,)
  57. raise
  58. output.append('# EOF\n')
  59. return ''.join(output).encode('utf-8')