From d57089bf8750d4a8b079f7347c9c84c63b1f5453 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 11 Nov 2024 22:15:37 +0100 Subject: [PATCH 1/2] Fix RotatingFileHandler bug where rotation could sometimes not happen correctly, fixes #1905 --- src/Monolog/Handler/RotatingFileHandler.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Monolog/Handler/RotatingFileHandler.php b/src/Monolog/Handler/RotatingFileHandler.php index 17745d221..25e78ade2 100644 --- a/src/Monolog/Handler/RotatingFileHandler.php +++ b/src/Monolog/Handler/RotatingFileHandler.php @@ -115,11 +115,14 @@ protected function write(array $record): void // on the first record written, if the log is new, we should rotate (once per day) if (null === $this->mustRotate) { $this->mustRotate = null === $this->url || !file_exists($this->url); + if ($this->mustRotate) { + $this->close(); // triggers rotation + } } if ($this->nextRotation <= $record['datetime']) { $this->mustRotate = true; - $this->close(); + $this->close(); // triggers rotation } parent::write($record); @@ -134,6 +137,8 @@ protected function rotate(): void $this->url = $this->getTimedFilename(); $this->nextRotation = new \DateTimeImmutable('tomorrow'); + $this->mustRotate = false; + // skip GC of old logs if files are unlimited if (0 === $this->maxFiles) { return; @@ -166,8 +171,6 @@ protected function rotate(): void restore_error_handler(); } } - - $this->mustRotate = false; } protected function getTimedFilename(): string From d2d0341604de8ca098af4546718aea35deeb4088 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 11 Nov 2024 22:29:51 +0100 Subject: [PATCH 2/2] Fix patch --- src/Monolog/Handler/RotatingFileHandler.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Monolog/Handler/RotatingFileHandler.php b/src/Monolog/Handler/RotatingFileHandler.php index 25e78ade2..2d0c1a72d 100644 --- a/src/Monolog/Handler/RotatingFileHandler.php +++ b/src/Monolog/Handler/RotatingFileHandler.php @@ -112,20 +112,22 @@ public function setFilenameFormat(string $filenameFormat, string $dateFormat): s */ protected function write(array $record): void { - // on the first record written, if the log is new, we should rotate (once per day) + // on the first record written, if the log is new, we rotate (once per day) after the log has been written so that the new file exists if (null === $this->mustRotate) { $this->mustRotate = null === $this->url || !file_exists($this->url); - if ($this->mustRotate) { - $this->close(); // triggers rotation - } } + // if the next rotation is expired, then we rotate immediately if ($this->nextRotation <= $record['datetime']) { $this->mustRotate = true; $this->close(); // triggers rotation } parent::write($record); + + if ($this->mustRotate) { + $this->close(); // triggers rotation + } } /**