StreamHandler.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. class StreamHandler extends AbstractProcessingHandler
  21. {
  22. protected const MAX_CHUNK_SIZE = 2147483647;
  23. /** @var resource|null */
  24. protected $stream;
  25. protected $url;
  26. /** @var string|null */
  27. private $errorMessage;
  28. protected $filePermission;
  29. protected $useLocking;
  30. private $dirCreated;
  31. /**
  32. * @param resource|string $stream If a missing path can't be created, an UnexpectedValueException will be thrown on first write
  33. * @param string|int $level The minimum logging level at which this handler will be triggered
  34. * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
  35. * @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
  36. * @param bool $useLocking Try to lock log file before doing any writes
  37. *
  38. * @throws \InvalidArgumentException If stream is not a resource or string
  39. */
  40. public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
  41. {
  42. parent::__construct($level, $bubble);
  43. if (is_resource($stream)) {
  44. $this->stream = $stream;
  45. stream_set_chunk_size($this->stream, self::MAX_CHUNK_SIZE);
  46. } elseif (is_string($stream)) {
  47. $this->url = Utils::canonicalizePath($stream);
  48. } else {
  49. throw new \InvalidArgumentException('A stream must either be a resource or a string.');
  50. }
  51. $this->filePermission = $filePermission;
  52. $this->useLocking = $useLocking;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function close(): void
  58. {
  59. if ($this->url && is_resource($this->stream)) {
  60. fclose($this->stream);
  61. }
  62. $this->stream = null;
  63. $this->dirCreated = null;
  64. }
  65. /**
  66. * Return the currently active stream if it is open
  67. *
  68. * @return resource|null
  69. */
  70. public function getStream()
  71. {
  72. return $this->stream;
  73. }
  74. /**
  75. * Return the stream URL if it was configured with a URL and not an active resource
  76. *
  77. * @return string|null
  78. */
  79. public function getUrl(): ?string
  80. {
  81. return $this->url;
  82. }
  83. /**
  84. * {@inheritdoc}
  85. */
  86. protected function write(array $record): void
  87. {
  88. if (!is_resource($this->stream)) {
  89. if (null === $this->url || '' === $this->url) {
  90. throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
  91. }
  92. $this->createDir();
  93. $this->errorMessage = null;
  94. set_error_handler([$this, 'customErrorHandler']);
  95. $this->stream = fopen($this->url, 'a');
  96. if ($this->filePermission !== null) {
  97. @chmod($this->url, $this->filePermission);
  98. }
  99. restore_error_handler();
  100. if (!is_resource($this->stream)) {
  101. $this->stream = null;
  102. throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $this->url));
  103. }
  104. stream_set_chunk_size($this->stream, self::MAX_CHUNK_SIZE);
  105. }
  106. if ($this->useLocking) {
  107. // ignoring errors here, there's not much we can do about them
  108. flock($this->stream, LOCK_EX);
  109. }
  110. $this->streamWrite($this->stream, $record);
  111. if ($this->useLocking) {
  112. flock($this->stream, LOCK_UN);
  113. }
  114. }
  115. /**
  116. * Write to stream
  117. * @param resource $stream
  118. * @param array $record
  119. */
  120. protected function streamWrite($stream, array $record): void
  121. {
  122. fwrite($stream, (string) $record['formatted']);
  123. }
  124. private function customErrorHandler($code, $msg): bool
  125. {
  126. $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
  127. return true;
  128. }
  129. private function getDirFromStream(string $stream): ?string
  130. {
  131. $pos = strpos($stream, '://');
  132. if ($pos === false) {
  133. return dirname($stream);
  134. }
  135. if ('file://' === substr($stream, 0, 7)) {
  136. return dirname(substr($stream, 7));
  137. }
  138. return null;
  139. }
  140. private function createDir(): void
  141. {
  142. // Do not try to create dir if it has already been tried.
  143. if ($this->dirCreated) {
  144. return;
  145. }
  146. $dir = $this->getDirFromStream($this->url);
  147. if (null !== $dir && !is_dir($dir)) {
  148. $this->errorMessage = null;
  149. set_error_handler([$this, 'customErrorHandler']);
  150. $status = mkdir($dir, 0777, true);
  151. restore_error_handler();
  152. if (false === $status && !is_dir($dir)) {
  153. throw new \UnexpectedValueException(sprintf('There is no existing directory at "%s" and it could not be created: '.$this->errorMessage, $dir));
  154. }
  155. }
  156. $this->dirCreated = true;
  157. }
  158. }