diff --git a/src/Illuminate/Database/Connection.php b/src/Illuminate/Database/Connection.php index 9910fe911b66..a23fb249f89e 100755 --- a/src/Illuminate/Database/Connection.php +++ b/src/Illuminate/Database/Connection.php @@ -154,6 +154,13 @@ class Connection implements ConnectionInterface */ protected $queryLog = []; + /** + * The maximum number of queries to keep in the query log. + * + * @var int + */ + protected $maxQueryLogSize = 1000; + /** * Indicates whether queries are being logged. * @@ -858,6 +865,10 @@ public function logQuery($query, $bindings, $time = null) if ($this->loggingQueries) { $this->queryLog[] = compact('query', 'bindings', 'time'); + + if (count($this->queryLog) > $this->maxQueryLogSize) { + $this->queryLog = array_slice($this->queryLog, -$this->maxQueryLogSize, $this->maxQueryLogSize, false); + } } } @@ -1569,6 +1580,29 @@ public function logging() return $this->loggingQueries; } + /** + * Set the maximum query log size. + * + * @param int $size + * @return $this + */ + public function setMaxQueryLogSize(int $size) + { + $this->maxQueryLogSize = max(1, $size); + + return $this; + } + + /** + * Get the maximum query log size. + * + * @return int + */ + public function getMaxQueryLogSize() + { + return $this->maxQueryLogSize; + } + /** * Get the name of the connected database. * diff --git a/tests/Database/DatabaseConnectionTest.php b/tests/Database/DatabaseConnectionTest.php index 164da72f6a58..2587c45a272b 100755 --- a/tests/Database/DatabaseConnectionTest.php +++ b/tests/Database/DatabaseConnectionTest.php @@ -549,6 +549,37 @@ protected function getMockConnection($methods = [], $pdo = null) return $connection; } + + public function testQueryLogSizeLimit() + { + $connection = $this->getMockConnection(); + $connection->enableQueryLog(); + $connection->setMaxQueryLogSize(3); + + $this->assertEquals(3, $connection->getMaxQueryLogSize()); + + for ($i = 0; $i < 5; $i++) { + $connection->logQuery('SELECT * FROM test WHERE id = ?', [$i], 10.0); + } + + $queryLog = $connection->getQueryLog(); + + $this->assertCount(3, $queryLog); + $this->assertEquals([2], $queryLog[0]['bindings']); + $this->assertEquals([3], $queryLog[1]['bindings']); + $this->assertEquals([4], $queryLog[2]['bindings']); + } + + public function testQueryLogSizeLimitMinimumValue() + { + $connection = $this->getMockConnection(); + + $connection->setMaxQueryLogSize(0); + $this->assertEquals(1, $connection->getMaxQueryLogSize()); + + $connection->setMaxQueryLogSize(-5); + $this->assertEquals(1, $connection->getMaxQueryLogSize()); + } } class DatabaseConnectionTestMockPDO extends PDO