RotatingFileHandler.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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 Boolean $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 Boolean $useLocking Try to lock log file before doing any writes
  40. */
  41. public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, $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 = 'Y-m-d';
  48. parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking);
  49. }
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function close()
  54. {
  55. parent::close();
  56. if (true === $this->mustRotate) {
  57. $this->rotate();
  58. }
  59. }
  60. public function setFilenameFormat($filenameFormat, $dateFormat)
  61. {
  62. if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
  63. throw new InvalidArgumentException(
  64. 'Invalid date format - format must be one of '.
  65. 'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '.
  66. 'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '.
  67. 'date formats using slashes, underscores and/or dots instead of dashes.'
  68. );
  69. }
  70. if (substr_count($filenameFormat, '{date}') === 0) {
  71. throw new InvalidArgumentException(
  72. 'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.'
  73. );
  74. }
  75. $this->filenameFormat = $filenameFormat;
  76. $this->dateFormat = $dateFormat;
  77. $this->url = $this->getTimedFilename();
  78. $this->close();
  79. }
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected function write(array $record)
  84. {
  85. // on the first record written, if the log is new, we should rotate (once per day)
  86. if (null === $this->mustRotate) {
  87. $this->mustRotate = !file_exists($this->url);
  88. }
  89. if ($this->nextRotation <= $record['datetime']) {
  90. $this->mustRotate = true;
  91. $this->close();
  92. }
  93. parent::write($record);
  94. }
  95. /**
  96. * Rotates the files.
  97. */
  98. protected function rotate()
  99. {
  100. // update filename
  101. $this->url = $this->getTimedFilename();
  102. $this->nextRotation = new \DateTimeImmutable('tomorrow');
  103. // skip GC of old logs if files are unlimited
  104. if (0 === $this->maxFiles) {
  105. return;
  106. }
  107. $logFiles = glob($this->getGlobPattern());
  108. if ($this->maxFiles >= count($logFiles)) {
  109. // no files to remove
  110. return;
  111. }
  112. // Sorting the files by name to remove the older ones
  113. usort($logFiles, function ($a, $b) {
  114. return strcmp($b, $a);
  115. });
  116. foreach (array_slice($logFiles, $this->maxFiles) as $file) {
  117. if (is_writable($file)) {
  118. // suppress errors here as unlink() might fail if two processes
  119. // are cleaning up/rotating at the same time
  120. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  121. });
  122. unlink($file);
  123. restore_error_handler();
  124. }
  125. }
  126. $this->mustRotate = false;
  127. }
  128. protected function getTimedFilename()
  129. {
  130. $fileInfo = pathinfo($this->filename);
  131. $timedFilename = str_replace(
  132. ['{filename}', '{date}'],
  133. [$fileInfo['filename'], date($this->dateFormat)],
  134. $fileInfo['dirname'] . '/' . $this->filenameFormat
  135. );
  136. if (!empty($fileInfo['extension'])) {
  137. $timedFilename .= '.'.$fileInfo['extension'];
  138. }
  139. return $timedFilename;
  140. }
  141. protected function getGlobPattern()
  142. {
  143. $fileInfo = pathinfo($this->filename);
  144. $glob = str_replace(
  145. ['{filename}', '{date}'],
  146. [$fileInfo['filename'], '*'],
  147. $fileInfo['dirname'] . '/' . $this->filenameFormat
  148. );
  149. if (!empty($fileInfo['extension'])) {
  150. $glob .= '.'.$fileInfo['extension'];
  151. }
  152. return $glob;
  153. }
  154. }