From 6228191bf2c5bb5e3303063c073dbf85a1715a2a Mon Sep 17 00:00:00 2001 From: Ilija Studen Date: Sun, 12 May 2024 20:13:32 +0200 Subject: [PATCH] Add query logger utility to the page --- src/QueryLogger/QueryLogger.php | 52 ++++++++++++++++++++++++ src/QueryLogger/QueryLoggerInterface.php | 17 ++++++++ 2 files changed, 69 insertions(+) create mode 100644 src/QueryLogger/QueryLogger.php create mode 100644 src/QueryLogger/QueryLoggerInterface.php diff --git a/src/QueryLogger/QueryLogger.php b/src/QueryLogger/QueryLogger.php new file mode 100644 index 0000000..8a91a96 --- /dev/null +++ b/src/QueryLogger/QueryLogger.php @@ -0,0 +1,52 @@ +. All rights reserved. + */ + +declare(strict_types=1); + +namespace ActiveCollab\DatabaseConnection\QueryLogger; + +use Psr\Log\LoggerInterface; +use Psr\Log\LogLevel; + +class QueryLogger implements QueryLoggerInterface +{ + private array $queries = []; + private float $executionTime = 0.0; + + public function __construct( + private LoggerInterface $logger, + private string $logLevel = LogLevel::DEBUG, + ) + { + } + + public function __invoke(string $querySql, float $queryExecutionTime): void + { + $this->logger->log( + $this->logLevel, + 'Query {query} ran in {time}s.', + [ + 'query' => $querySql, + 'time' => round($queryExecutionTime, 5), + ], + ); + + $this->queries[] = $querySql; + $this->executionTime += $queryExecutionTime; + } + + public function getNumberOfQueries(): int + { + return count($this->queries); + } + + public function getExecutionTime(): float + { + return round($this->executionTime, 5); + } +} diff --git a/src/QueryLogger/QueryLoggerInterface.php b/src/QueryLogger/QueryLoggerInterface.php new file mode 100644 index 0000000..f3f4555 --- /dev/null +++ b/src/QueryLogger/QueryLoggerInterface.php @@ -0,0 +1,17 @@ +. All rights reserved. + */ + +declare(strict_types=1); + +namespace ActiveCollab\DatabaseConnection\QueryLogger; + +interface QueryLoggerInterface +{ + public function getNumberOfQueries(): int; + public function getExecutionTime(): float; +}