StreamHandler.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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 Monolog\Level;
  12. use Monolog\Utils;
  13. use Monolog\LogRecord;
  14. /**
  15. * Stores to any stream resource
  16. *
  17. * Can be used to store into php://stderr, remote and local files, etc.
  18. *
  19. * @author Jordi Boggiano <j.boggiano@seld.be>
  20. */
  21. class StreamHandler extends AbstractProcessingHandler
  22. {
  23. /** @const int */
  24. protected const MAX_CHUNK_SIZE = 2147483647;
  25. /** @const int 10MB */
  26. protected const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024;
  27. protected int $streamChunkSize;
  28. /** @var resource|null */
  29. protected $stream;
  30. /** @var ?string */
  31. protected $url = null;
  32. /** @var ?string */
  33. private $errorMessage = null;
  34. /** @var ?int */
  35. protected $filePermission;
  36. protected bool $useLocking;
  37. /** @var true|null */
  38. private ?bool $dirCreated = null;
  39. /**
  40. * @param resource|string $stream If a missing path can't be created, an UnexpectedValueException will be thrown on first write
  41. * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
  42. * @param bool $useLocking Try to lock log file before doing any writes
  43. *
  44. * @throws \InvalidArgumentException If stream is not a resource or string
  45. */
  46. public function __construct($stream, $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
  47. {
  48. parent::__construct($level, $bubble);
  49. if (($phpMemoryLimit = Utils::expandIniShorthandBytes(ini_get('memory_limit'))) !== false) {
  50. if ($phpMemoryLimit > 0) {
  51. // use max 10% of allowed memory for the chunk size, and at least 100KB
  52. $this->streamChunkSize = min(static::MAX_CHUNK_SIZE, max((int) ($phpMemoryLimit / 10), 100 * 1024));
  53. } else {
  54. // memory is unlimited, set to the default 10MB
  55. $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE;
  56. }
  57. } else {
  58. // no memory limit information, set to the default 10MB
  59. $this->streamChunkSize = static::DEFAULT_CHUNK_SIZE;
  60. }
  61. if (is_resource($stream)) {
  62. $this->stream = $stream;
  63. stream_set_chunk_size($this->stream, $this->streamChunkSize);
  64. } elseif (is_string($stream)) {
  65. $this->url = Utils::canonicalizePath($stream);
  66. } else {
  67. throw new \InvalidArgumentException('A stream must either be a resource or a string.');
  68. }
  69. $this->filePermission = $filePermission;
  70. $this->useLocking = $useLocking;
  71. }
  72. /**
  73. * @inheritDoc
  74. */
  75. public function close(): void
  76. {
  77. if ($this->url && is_resource($this->stream)) {
  78. fclose($this->stream);
  79. }
  80. $this->stream = null;
  81. $this->dirCreated = null;
  82. }
  83. /**
  84. * Return the currently active stream if it is open
  85. *
  86. * @return resource|null
  87. */
  88. public function getStream()
  89. {
  90. return $this->stream;
  91. }
  92. /**
  93. * Return the stream URL if it was configured with a URL and not an active resource
  94. */
  95. public function getUrl(): ?string
  96. {
  97. return $this->url;
  98. }
  99. public function getStreamChunkSize(): int
  100. {
  101. return $this->streamChunkSize;
  102. }
  103. /**
  104. * @inheritDoc
  105. */
  106. protected function write(LogRecord $record): void
  107. {
  108. if (!is_resource($this->stream)) {
  109. $url = $this->url;
  110. if (null === $url || '' === $url) {
  111. throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().' . Utils::getRecordMessageForException($record));
  112. }
  113. $this->createDir($url);
  114. $this->errorMessage = null;
  115. set_error_handler([$this, 'customErrorHandler']);
  116. $stream = fopen($url, 'a');
  117. if ($this->filePermission !== null) {
  118. @chmod($url, $this->filePermission);
  119. }
  120. restore_error_handler();
  121. if (!is_resource($stream)) {
  122. $this->stream = null;
  123. throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url) . Utils::getRecordMessageForException($record));
  124. }
  125. stream_set_chunk_size($stream, $this->streamChunkSize);
  126. $this->stream = $stream;
  127. }
  128. $stream = $this->stream;
  129. if (!is_resource($stream)) {
  130. throw new \LogicException('No stream was opened yet' . Utils::getRecordMessageForException($record));
  131. }
  132. if ($this->useLocking) {
  133. // ignoring errors here, there's not much we can do about them
  134. flock($stream, LOCK_EX);
  135. }
  136. $this->streamWrite($stream, $record);
  137. if ($this->useLocking) {
  138. flock($stream, LOCK_UN);
  139. }
  140. }
  141. /**
  142. * Write to stream
  143. * @param resource $stream
  144. */
  145. protected function streamWrite($stream, LogRecord $record): void
  146. {
  147. fwrite($stream, (string) $record->formatted);
  148. }
  149. private function customErrorHandler(int $code, string $msg): bool
  150. {
  151. $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
  152. return true;
  153. }
  154. private function getDirFromStream(string $stream): ?string
  155. {
  156. $pos = strpos($stream, '://');
  157. if ($pos === false) {
  158. return dirname($stream);
  159. }
  160. if ('file://' === substr($stream, 0, 7)) {
  161. return dirname(substr($stream, 7));
  162. }
  163. return null;
  164. }
  165. private function createDir(string $url): void
  166. {
  167. // Do not try to create dir if it has already been tried.
  168. if ($this->dirCreated) {
  169. return;
  170. }
  171. $dir = $this->getDirFromStream($url);
  172. if (null !== $dir && !is_dir($dir)) {
  173. $this->errorMessage = null;
  174. set_error_handler([$this, 'customErrorHandler']);
  175. $status = mkdir($dir, 0777, true);
  176. restore_error_handler();
  177. if (false === $status && !is_dir($dir)) {
  178. throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and it could not be created: '.$this->errorMessage, $dir));
  179. }
  180. }
  181. $this->dirCreated = true;
  182. }
  183. }