RotatingFileHandler.php 5.6 KB

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