This repository was archived by the owner on Oct 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathRenderTextFormat.php
More file actions
55 lines (46 loc) · 1.73 KB
/
RenderTextFormat.php
File metadata and controls
55 lines (46 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace Prometheus;
class RenderTextFormat implements RendererInterface
{
const MIME_TYPE = 'text/plain; version=0.0.4';
/**
* @param MetricFamilySamples[] $metrics
* @return string
*/
public function render(array $metrics)
{
usort($metrics, function(MetricFamilySamples $a, MetricFamilySamples $b)
{
return strcmp($a->getName(), $b->getName());
});
$lines = array();
foreach ($metrics as $metric) {
$lines[] = "# HELP " . $metric->getName() . " {$metric->getHelp()}";
$lines[] = "# TYPE " . $metric->getName() . " {$metric->getType()}";
foreach ($metric->getSamples() as $sample) {
$lines[] = $this->renderSample($metric, $sample);
}
}
return implode("\n", $lines) . "\n";
}
private function renderSample(MetricFamilySamples $metric, Sample $sample)
{
$escapedLabels = array();
$labelNames = $metric->getLabelNames();
if ($metric->hasLabelNames() || $sample->hasLabelNames()) {
$labels = array_combine(array_merge($labelNames, $sample->getLabelNames()), $sample->getLabelValues());
foreach ($labels as $labelName => $labelValue) {
$escapedLabels[] = $labelName . '="' . $this->escapeLabelValue($labelValue) . '"';
}
return $sample->getName() . '{' . implode(',', $escapedLabels) . '} ' . $sample->getValue();
}
return $sample->getName() . ' ' . $sample->getValue();
}
private function escapeLabelValue($v)
{
$v = str_replace("\\", "\\\\", $v);
$v = str_replace("\n", "\\n", $v);
$v = str_replace("\"", "\\\"", $v);
return $v;
}
}