StreamHandler.php 7.3 KB

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