From 6a6c280c3bb895fb30345961268a5748c084439b Mon Sep 17 00:00:00 2001 From: dmitry krokhin Date: Tue, 17 Aug 2021 20:55:37 +0300 Subject: [PATCH] prometheus metrics order fix --- src/Metrics/Exporter/PrometheusExporter.php | 12 +++++----- tests/Metrics/ExporterTest.php | 26 +++++++++++++++++++++ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/src/Metrics/Exporter/PrometheusExporter.php b/src/Metrics/Exporter/PrometheusExporter.php index df4c1fa..af6e092 100644 --- a/src/Metrics/Exporter/PrometheusExporter.php +++ b/src/Metrics/Exporter/PrometheusExporter.php @@ -17,16 +17,14 @@ public function toFile(string $path, string $prefix = '', array $labels = []): v public function toString(string $prefix = '', array $labels = []): string { - $info = []; $result = []; foreach ($this->toArray($labels) as $row) { $key = $prefix . $row['key']; - if (!array_key_exists($key, $info)) { - $result[] = sprintf('# HELP %s %s', $key, $row['help']); - $result[] = sprintf('# TYPE %s %s', $key, $row['type']); - $info[$key] = true; + if (!array_key_exists($key . '!h', $result)) { + $result[$key . '!h'] = sprintf('# HELP %s %s', $key, $row['help']); + $result[$key . '!t'] = sprintf('# TYPE %s %s', $key, $row['type']); } $rowLabels = []; @@ -37,9 +35,11 @@ public function toString(string $prefix = '', array $labels = []): string $key .= '{' . implode(',', $rowLabels) . '}'; } - $result[] = sprintf('%s %s', $key, $row['value']); + $result[$key] = sprintf('%s %s', $key, $row['value']); } + ksort($result); + return implode(PHP_EOL, $result); } } diff --git a/tests/Metrics/ExporterTest.php b/tests/Metrics/ExporterTest.php index 5f48ed2..6cead30 100644 --- a/tests/Metrics/ExporterTest.php +++ b/tests/Metrics/ExporterTest.php @@ -80,6 +80,32 @@ public function testExporter(): void $this->assertCount(2, explode('HELP svc_request_counter', $result)); } + + public function testMetricsOrder() + { + $registry = new Registry(); + $registry->set('todo', 1, ['queue' => 'web.bundle']); + $registry->set('complete', 2, ['queue' => 'flow.promote']); + $registry->set('todo', 3, ['queue' => 'space.housekeeping']); + + $info = new Info(); + $info->set('todo', 'waiting'); + $info->set('complete', 'complete'); + + $string = (new PrometheusExporter($registry, $info))->toString(); + + $shouldbe = implode(PHP_EOL, [ + '# HELP complete complete', + '# TYPE complete gauge', + 'complete{queue="flow.promote"} 2', + '# HELP todo waiting', + '# TYPE todo gauge', + 'todo{queue="space.housekeeping"} 3', + 'todo{queue="web.bundle"} 1', + ]); + $this->assertSame($string, $shouldbe); + } + public function testExtraLabels() { $registry = new Registry();