RotatingFileHandler.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use InvalidArgumentException;
  12. use Monolog\Logger;
  13. /**
  14. * Stores logs to files that are rotated every day and a limited number of files are kept.
  15. *
  16. * This rotation is only intended to be used as a workaround. Using logrotate to
  17. * handle the rotation is strongly encouraged when you can use it.
  18. *
  19. * @author Christophe Coevoet <stof@notk.org>
  20. * @author Jordi Boggiano <j.boggiano@seld.be>
  21. */
  22. class RotatingFileHandler extends StreamHandler
  23. {
  24. const FILE_PER_DAY = 'Y-m-d';
  25. const FILE_PER_MONTH = 'Y-m';
  26. const FILE_PER_YEAR = 'Y';
  27. protected $filename;
  28. protected $maxFiles;
  29. protected $mustRotate;
  30. protected $nextRotation;
  31. protected $filenameFormat;
  32. protected $dateFormat;
  33. /**
  34. * @param string $filename
  35. * @param int $maxFiles The maximal amount of files to keep (0 means unlimited)
  36. * @param int $level The minimum logging level at which this handler will be triggered
  37. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  38. * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
  39. * @param bool $useLocking Try to lock log file before doing any writes
  40. */
  41. public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false)
  42. {
  43. $this->filename = $filename;
  44. $this->maxFiles = (int) $maxFiles;
  45. $this->nextRotation = new \DateTimeImmutable('tomorrow');
  46. $this->filenameFormat = '{filename}-{date}';
  47. $this->dateFormat = self::FILE_PER_DAY;
  48. parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking);
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function close(): void
  54. {
  55. parent::close();
  56. if (true === $this->mustRotate) {
  57. $this->rotate();
  58. }
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function reset()
  64. {
  65. parent::reset();
  66. if (true === $this->mustRotate) {
  67. $this->rotate();
  68. }
  69. }
  70. public function setFilenameFormat($filenameFormat, $dateFormat)
  71. {
  72. if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
  73. throw new InvalidArgumentException(
  74. 'Invalid date format - format must be one of '.
  75. 'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '.
  76. 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '.
  77. 'date formats using slashes, underscores and/or dots instead of dashes.'
  78. );
  79. }
  80. if (substr_count($filenameFormat, '{date}') === 0) {
  81. throw new InvalidArgumentException(
  82. 'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.'
  83. );
  84. }
  85. $this->filenameFormat = $filenameFormat;
  86. $this->dateFormat = $dateFormat;
  87. $this->url = $this->getTimedFilename();
  88. $this->close();
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. protected function write(array $record): void
  94. {
  95. // on the first record written, if the log is new, we should rotate (once per day)
  96. if (null === $this->mustRotate) {
  97. $this->mustRotate = !file_exists($this->url);
  98. }
  99. if ($this->nextRotation <= $record['datetime']) {
  100. $this->mustRotate = true;
  101. $this->close();
  102. }
  103. parent::write($record);
  104. }
  105. /**
  106. * Rotates the files.
  107. */
  108. protected function rotate(): void
  109. {
  110. // update filename
  111. $this->url = $this->getTimedFilename();
  112. $this->nextRotation = new \DateTimeImmutable('tomorrow');
  113. // skip GC of old logs if files are unlimited
  114. if (0 === $this->maxFiles) {
  115. return;
  116. }
  117. $logFiles = glob($this->getGlobPattern());
  118. if ($this->maxFiles >= count($logFiles)) {
  119. // no files to remove
  120. return;
  121. }
  122. // Sorting the files by name to remove the older ones
  123. usort($logFiles, function ($a, $b) {
  124. return strcmp($b, $a);
  125. });
  126. foreach (array_slice($logFiles, $this->maxFiles) as $file) {
  127. if (is_writable($file)) {
  128. // suppress errors here as unlink() might fail if two processes
  129. // are cleaning up/rotating at the same time
  130. set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool {
  131. return false;
  132. });
  133. unlink($file);
  134. restore_error_handler();
  135. }
  136. }
  137. $this->mustRotate = false;
  138. }
  139. protected function getTimedFilename()
  140. {
  141. $fileInfo = pathinfo($this->filename);
  142. $timedFilename = str_replace(
  143. ['{filename}', '{date}'],
  144. [$fileInfo['filename'], date($this->dateFormat)],
  145. $fileInfo['dirname'] . '/' . $this->filenameFormat
  146. );
  147. if (!empty($fileInfo['extension'])) {
  148. $timedFilename .= '.'.$fileInfo['extension'];
  149. }
  150. return $timedFilename;
  151. }
  152. protected function getGlobPattern()
  153. {
  154. $fileInfo = pathinfo($this->filename);
  155. $glob = str_replace(
  156. ['{filename}', '{date}'],
  157. [$fileInfo['filename'], '[0-9][0-9][0-9][0-9]*'],
  158. $fileInfo['dirname'] . '/' . $this->filenameFormat
  159. );
  160. if (!empty($fileInfo['extension'])) {
  161. $glob .= '.'.$fileInfo['extension'];
  162. }
  163. return $glob;
  164. }
  165. }