FileTarget.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\log;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\helpers\FileHelper;
  11. /**
  12. * FileTarget records log messages in a file.
  13. *
  14. * The log file is specified via [[logFile]]. If the size of the log file exceeds
  15. * [[maxFileSize]] (in kilo-bytes), a rotation will be performed, which renames
  16. * the current log file by suffixing the file name with '.1'. All existing log
  17. * files are moved backwards by one place, i.e., '.2' to '.3', '.1' to '.2', and so on.
  18. * The property [[maxLogFiles]] specifies how many history files to keep.
  19. *
  20. * Since 2.0.46 rotation of the files is done only by copy and the
  21. * `rotateByCopy` property is deprecated.
  22. *
  23. * @author Qiang Xue <qiang.xue@gmail.com>
  24. * @since 2.0
  25. */
  26. class FileTarget extends Target
  27. {
  28. /**
  29. * @var string|null log file path or [path alias](guide:concept-aliases). If not set, it will use the "@runtime/logs/app.log" file.
  30. * The directory containing the log files will be automatically created if not existing.
  31. */
  32. public $logFile;
  33. /**
  34. * @var bool whether log files should be rotated when they reach a certain [[maxFileSize|maximum size]].
  35. * Log rotation is enabled by default. This property allows you to disable it, when you have configured
  36. * an external tools for log rotation on your server.
  37. * @since 2.0.3
  38. */
  39. public $enableRotation = true;
  40. /**
  41. * @var int maximum log file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
  42. */
  43. public $maxFileSize = 10240; // in KB
  44. /**
  45. * @var int number of log files used for rotation. Defaults to 5.
  46. */
  47. public $maxLogFiles = 5;
  48. /**
  49. * @var int|null the permission to be set for newly created log files.
  50. * This value will be used by PHP chmod() function. No umask will be applied.
  51. * If not set, the permission will be determined by the current environment.
  52. */
  53. public $fileMode;
  54. /**
  55. * @var int the permission to be set for newly created directories.
  56. * This value will be used by PHP chmod() function. No umask will be applied.
  57. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  58. * but read-only for other users.
  59. */
  60. public $dirMode = 0775;
  61. /**
  62. * @var bool Whether to rotate log files by copy and truncate in contrast to rotation by
  63. * renaming files. Defaults to `true` to be more compatible with log tailers and windows
  64. * systems which do not play well with rename on open files. Rotation by renaming however is
  65. * a bit faster.
  66. *
  67. * The problem with windows systems where the [rename()](https://www.php.net/manual/en/function.rename.php)
  68. * function does not work with files that are opened by some process is described in a
  69. * [comment by Martin Pelletier](https://www.php.net/manual/en/function.rename.php#102274) in
  70. * the PHP documentation. By setting rotateByCopy to `true` you can work
  71. * around this.
  72. * @deprecated since 2.0.46 and setting it to false has no effect anymore
  73. * since rotating is now always done by copy.
  74. */
  75. public $rotateByCopy = true;
  76. /**
  77. * Initializes the route.
  78. * This method is invoked after the route is created by the route manager.
  79. */
  80. public function init()
  81. {
  82. parent::init();
  83. if ($this->logFile === null) {
  84. $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log';
  85. } else {
  86. $this->logFile = Yii::getAlias($this->logFile);
  87. }
  88. if ($this->maxLogFiles < 1) {
  89. $this->maxLogFiles = 1;
  90. }
  91. if ($this->maxFileSize < 1) {
  92. $this->maxFileSize = 1;
  93. }
  94. }
  95. /**
  96. * Writes log messages to a file.
  97. * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
  98. * @throws InvalidConfigException if unable to open the log file for writing
  99. * @throws LogRuntimeException if unable to write complete log to file
  100. */
  101. public function export()
  102. {
  103. $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";
  104. if (trim($text) === '') {
  105. return; // No messages to export, so we exit the function early
  106. }
  107. if (strpos($this->logFile, '://') === false || strncmp($this->logFile, 'file://', 7) === 0) {
  108. $logPath = dirname($this->logFile);
  109. FileHelper::createDirectory($logPath, $this->dirMode, true);
  110. }
  111. if (($fp = @fopen($this->logFile, 'a')) === false) {
  112. throw new InvalidConfigException("Unable to append to log file: {$this->logFile}");
  113. }
  114. @flock($fp, LOCK_EX);
  115. if ($this->enableRotation) {
  116. // clear stat cache to ensure getting the real current file size and not a cached one
  117. // this may result in rotating twice when cached file size is used on subsequent calls
  118. clearstatcache();
  119. }
  120. if ($this->enableRotation && @filesize($this->logFile) > $this->maxFileSize * 1024) {
  121. $this->rotateFiles();
  122. }
  123. $writeResult = @fwrite($fp, $text);
  124. if ($writeResult === false) {
  125. $error = error_get_last();
  126. throw new LogRuntimeException("Unable to export log through file ({$this->logFile})!: {$error['message']}");
  127. }
  128. $textSize = strlen($text);
  129. if ($writeResult < $textSize) {
  130. throw new LogRuntimeException("Unable to export whole log through file ({$this->logFile})! Wrote $writeResult out of $textSize bytes.");
  131. }
  132. @fflush($fp);
  133. @flock($fp, LOCK_UN);
  134. @fclose($fp);
  135. if ($this->fileMode !== null) {
  136. @chmod($this->logFile, $this->fileMode);
  137. }
  138. }
  139. /**
  140. * Rotates log files.
  141. */
  142. protected function rotateFiles()
  143. {
  144. $file = $this->logFile;
  145. for ($i = $this->maxLogFiles; $i >= 0; --$i) {
  146. // $i == 0 is the original log file
  147. $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
  148. if (is_file($rotateFile)) {
  149. // suppress errors because it's possible multiple processes enter into this section
  150. if ($i === $this->maxLogFiles) {
  151. @unlink($rotateFile);
  152. continue;
  153. }
  154. $newFile = $this->logFile . '.' . ($i + 1);
  155. $this->rotateByCopy($rotateFile, $newFile);
  156. if ($i === 0) {
  157. $this->clearLogFile($rotateFile);
  158. }
  159. }
  160. }
  161. }
  162. /***
  163. * Clear log file without closing any other process open handles
  164. * @param string $rotateFile
  165. */
  166. private function clearLogFile($rotateFile)
  167. {
  168. if ($filePointer = @fopen($rotateFile, 'a')) {
  169. @ftruncate($filePointer, 0);
  170. @fclose($filePointer);
  171. }
  172. }
  173. /***
  174. * Copy rotated file into new file
  175. * @param string $rotateFile
  176. * @param string $newFile
  177. */
  178. private function rotateByCopy($rotateFile, $newFile)
  179. {
  180. @copy($rotateFile, $newFile);
  181. if ($this->fileMode !== null) {
  182. @chmod($newFile, $this->fileMode);
  183. }
  184. }
  185. }