FileTarget.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. $logPath = dirname($this->logFile);
  99. FileHelper::createDirectory($logPath, $this->dirMode, true);
  100. $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";
  101. if (($fp = @fopen($this->logFile, 'a')) === false) {
  102. throw new InvalidConfigException("Unable to append to log file: {$this->logFile}");
  103. }
  104. @flock($fp, LOCK_EX);
  105. if ($this->enableRotation) {
  106. // clear stat cache to ensure getting the real current file size and not a cached one
  107. // this may result in rotating twice when cached file size is used on subsequent calls
  108. clearstatcache();
  109. }
  110. if ($this->enableRotation && @filesize($this->logFile) > $this->maxFileSize * 1024) {
  111. @flock($fp, LOCK_UN);
  112. @fclose($fp);
  113. $this->rotateFiles();
  114. $writeResult = @file_put_contents($this->logFile, $text, FILE_APPEND | LOCK_EX);
  115. if ($writeResult === false) {
  116. $error = error_get_last();
  117. throw new LogRuntimeException("Unable to export log through file!: {$error['message']}");
  118. }
  119. $textSize = strlen($text);
  120. if ($writeResult < $textSize) {
  121. throw new LogRuntimeException("Unable to export whole log through file! Wrote $writeResult out of $textSize bytes.");
  122. }
  123. } else {
  124. $writeResult = @fwrite($fp, $text);
  125. if ($writeResult === false) {
  126. $error = error_get_last();
  127. throw new LogRuntimeException("Unable to export log through file!: {$error['message']}");
  128. }
  129. $textSize = strlen($text);
  130. if ($writeResult < $textSize) {
  131. throw new LogRuntimeException("Unable to export whole log through file! Wrote $writeResult out of $textSize bytes.");
  132. }
  133. @flock($fp, LOCK_UN);
  134. @fclose($fp);
  135. }
  136. if ($this->fileMode !== null) {
  137. @chmod($this->logFile, $this->fileMode);
  138. }
  139. }
  140. /**
  141. * Rotates log files.
  142. */
  143. protected function rotateFiles()
  144. {
  145. $file = $this->logFile;
  146. for ($i = $this->maxLogFiles; $i >= 0; --$i) {
  147. // $i == 0 is the original log file
  148. $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
  149. if (is_file($rotateFile)) {
  150. // suppress errors because it's possible multiple processes enter into this section
  151. if ($i === $this->maxLogFiles) {
  152. @unlink($rotateFile);
  153. continue;
  154. }
  155. $newFile = $this->logFile . '.' . ($i + 1);
  156. $this->rotateByCopy ? $this->rotateByCopy($rotateFile, $newFile) : $this->rotateByRename($rotateFile, $newFile);
  157. if ($i === 0) {
  158. $this->clearLogFile($rotateFile);
  159. }
  160. }
  161. }
  162. }
  163. /***
  164. * Clear log file without closing any other process open handles
  165. * @param string $rotateFile
  166. */
  167. private function clearLogFile($rotateFile)
  168. {
  169. if ($filePointer = @fopen($rotateFile, 'a')) {
  170. @ftruncate($filePointer, 0);
  171. @fclose($filePointer);
  172. }
  173. }
  174. /***
  175. * Copy rotated file into new file
  176. * @param string $rotateFile
  177. * @param string $newFile
  178. */
  179. private function rotateByCopy($rotateFile, $newFile)
  180. {
  181. @copy($rotateFile, $newFile);
  182. if ($this->fileMode !== null) {
  183. @chmod($newFile, $this->fileMode);
  184. }
  185. }
  186. /**
  187. * Renames rotated file into new file
  188. * @param string $rotateFile
  189. * @param string $newFile
  190. */
  191. private function rotateByRename($rotateFile, $newFile)
  192. {
  193. @rename($rotateFile, $newFile);
  194. }
  195. }