Skip to content

Commit

Permalink
prometheus exporter decimals configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
nekufa committed Feb 17, 2023
1 parent f821ba1 commit 92fd10c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Metrics/Exporter/PrometheusExporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@

class PrometheusExporter extends Exporter
{
private int $decimals = 3;

public function setDecimals(int $decimals): self
{
$this->decimals = $decimals;
return $this;
}

public function toFile(string $path, string $prefix = '', array $labels = []): void
{
file_put_contents($path, $this->toString($prefix, $labels));
Expand All @@ -35,7 +43,12 @@ public function toString(string $prefix = '', array $labels = []): string
$key .= '{' . implode(',', $rowLabels) . '}';
}

$result[$key . '_'] = sprintf('%s %s', $key, $row['value']);
$value = $row['value'];
if (is_float($value)) {
$value = number_format($value, $this->decimals);
}

$result[$key . '_'] = sprintf('%s %s', $key, $value);
}

ksort($result);
Expand Down
25 changes: 25 additions & 0 deletions tests/Metrics/ExporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,31 @@ public function testExporter(): void
$this->assertCount(2, explode('HELP svc_request_counter', $result));
}

public function testFloat()
{
$registry = new Registry();
$timestamp = microtime(true);
usleep(40 * 1000);
$registry->set('tester', microtime(true) - $timestamp);

$info = new Info();
$info->set('tester', 'float value');

$exporter = new PrometheusExporter($registry, $info);

$exporter->setDecimals(3);
$this->assertEquals("tester 0.040", explode(PHP_EOL, $exporter->toString())[2]);

$exporter->setDecimals(2);
$this->assertEquals("tester 0.04", explode(PHP_EOL, $exporter->toString())[2]);

$exporter->setDecimals(1);
$this->assertEquals("tester 0.0", explode(PHP_EOL, $exporter->toString())[2]);

$exporter->setDecimals(0);
$this->assertEquals("tester 0", explode(PHP_EOL, $exporter->toString())[2]);
}

public function testMetricsOrder()
{
$registry = new Registry();
Expand Down

0 comments on commit 92fd10c

Please sign in to comment.