FileTarget.php 7.8 KB

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