diff --git a/src/Metrics/Exporter/PrometheusExporter.php b/src/Metrics/Exporter/PrometheusExporter.php index a3bb27d..576e605 100644 --- a/src/Metrics/Exporter/PrometheusExporter.php +++ b/src/Metrics/Exporter/PrometheusExporter.php @@ -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)); @@ -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); diff --git a/tests/Metrics/ExporterTest.php b/tests/Metrics/ExporterTest.php index d357a8a..8d4b6e6 100644 --- a/tests/Metrics/ExporterTest.php +++ b/tests/Metrics/ExporterTest.php @@ -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();