diff --git a/src/Monolog/Handler/RotatingFileHandler.php b/src/Monolog/Handler/RotatingFileHandler.php index 682542c3..cfb0d5aa 100644 --- a/src/Monolog/Handler/RotatingFileHandler.php +++ b/src/Monolog/Handler/RotatingFileHandler.php @@ -20,12 +20,14 @@ use Monolog\Logger; * handle the rotation is strongly encouraged when you can use it. * * @author Christophe Coevoet + * @author Jordi Boggiano */ class RotatingFileHandler extends StreamHandler { protected $filename; protected $maxFiles; protected $mustRotate; + protected $nextRotation; /** * @param string $filename @@ -37,19 +39,9 @@ class RotatingFileHandler extends StreamHandler { $this->filename = $filename; $this->maxFiles = (int) $maxFiles; + $this->nextRotation = new \DateTime('tomorrow'); - $fileInfo = pathinfo($this->filename); - $timedFilename = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-'.date('Y-m-d'); - if (!empty($fileInfo['extension'])) { - $timedFilename .= '.'.$fileInfo['extension']; - } - - // disable rotation upfront if files are unlimited - if (0 === $this->maxFiles) { - $this->mustRotate = false; - } - - parent::__construct($timedFilename, $level, $bubble); + parent::__construct($this->getTimedFilename(), $level, $bubble); } /** @@ -74,6 +66,11 @@ class RotatingFileHandler extends StreamHandler $this->mustRotate = !file_exists($this->url); } + if ($this->nextRotation < $record['datetime']) { + $this->mustRotate = true; + $this->close(); + } + parent::write($record); } @@ -82,6 +79,15 @@ class RotatingFileHandler extends StreamHandler */ protected function rotate() { + // update filename + $this->url = $this->getTimedFilename(); + $this->nextRotation = new \DateTime('tomorrow'); + + // skip GC of old logs if files are unlimited + if (0 === $this->maxFiles) { + return; + } + $fileInfo = pathinfo($this->filename); $glob = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-*'; if (!empty($fileInfo['extension'])) { @@ -106,4 +112,15 @@ class RotatingFileHandler extends StreamHandler } } } + + protected function getTimedFilename() + { + $fileInfo = pathinfo($this->filename); + $timedFilename = $fileInfo['dirname'].'/'.$fileInfo['filename'].'-'.date('Y-m-d'); + if (!empty($fileInfo['extension'])) { + $timedFilename .= '.'.$fileInfo['extension']; + } + + return $timedFilename; + } }