-
Notifications
You must be signed in to change notification settings - Fork 1
/
FetcherExporter.php
58 lines (46 loc) · 1.43 KB
/
FetcherExporter.php
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
56
57
58
<?php
declare(strict_types=1);
namespace Zlodes\PrometheusClient\Exporter;
use Zlodes\PrometheusClient\Fetcher\Fetcher;
final class FetcherExporter implements Exporter
{
public function __construct(
private readonly Fetcher $fetcher,
) {
}
public function export(): iterable
{
foreach ($this->fetcher->fetch() as $fetchedMetric) {
$metric = $fetchedMetric->metric;
$metricStrings = [
"# HELP {$metric->name} {$metric->help}",
"# TYPE {$metric->name} {$metric->getPrometheusType()}",
];
foreach ($fetchedMetric->values as $value) {
$metricStrings[] = sprintf(
"%s%s %s",
$value->metricNameWithLabels->metricName,
$this->buildLabelsString($value->metricNameWithLabels->labels),
$value->value
);
}
yield implode(PHP_EOL, $metricStrings);
}
}
/**
* @param array<string, string> $labels
*
* @return string
*/
private function buildLabelsString(array $labels): string
{
if ($labels === []) {
return '';
}
$formattedLabels = [];
foreach ($labels as $labelName => $labelValue) {
$formattedLabels[] = "$labelName=\"$labelValue\"";
}
return '{' . implode(',', $formattedLabels) . '}';
}
}