Skip to content

Commit

Permalink
prometheus metrics order fix
Browse files Browse the repository at this point in the history
  • Loading branch information
nekufa committed Aug 17, 2021
1 parent b10ac02 commit 6a6c280
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/Metrics/Exporter/PrometheusExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [];
Expand All @@ -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);
}
}
26 changes: 26 additions & 0 deletions tests/Metrics/ExporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 6a6c280

Please sign in to comment.