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; +}