Logger.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  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 Symfony\Component\HttpKernel\Log;
  11. use Psr\Log\AbstractLogger;
  12. use Psr\Log\InvalidArgumentException;
  13. use Psr\Log\LogLevel;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. /**
  17. * Minimalist PSR-3 logger designed to write in stderr or any other stream.
  18. *
  19. * @author Kévin Dunglas <dunglas@gmail.com>
  20. */
  21. class Logger extends AbstractLogger implements DebugLoggerInterface
  22. {
  23. private const LEVELS = [
  24. LogLevel::DEBUG => 0,
  25. LogLevel::INFO => 1,
  26. LogLevel::NOTICE => 2,
  27. LogLevel::WARNING => 3,
  28. LogLevel::ERROR => 4,
  29. LogLevel::CRITICAL => 5,
  30. LogLevel::ALERT => 6,
  31. LogLevel::EMERGENCY => 7,
  32. ];
  33. private const PRIORITIES = [
  34. LogLevel::DEBUG => 100,
  35. LogLevel::INFO => 200,
  36. LogLevel::NOTICE => 250,
  37. LogLevel::WARNING => 300,
  38. LogLevel::ERROR => 400,
  39. LogLevel::CRITICAL => 500,
  40. LogLevel::ALERT => 550,
  41. LogLevel::EMERGENCY => 600,
  42. ];
  43. private int $minLevelIndex;
  44. private \Closure $formatter;
  45. private bool $debug = false;
  46. private array $logs = [];
  47. private array $errorCount = [];
  48. /** @var resource|null */
  49. private $handle;
  50. /**
  51. * @param string|resource|null $output
  52. */
  53. public function __construct(?string $minLevel = null, $output = null, ?callable $formatter = null, private readonly ?RequestStack $requestStack = null, bool $debug = false)
  54. {
  55. if (null === $minLevel) {
  56. $minLevel = null === $output || 'php://stdout' === $output || 'php://stderr' === $output ? LogLevel::ERROR : LogLevel::WARNING;
  57. if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
  58. $minLevel = match ((int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'])) {
  59. -1 => LogLevel::ERROR,
  60. 1 => LogLevel::NOTICE,
  61. 2 => LogLevel::INFO,
  62. 3 => LogLevel::DEBUG,
  63. default => $minLevel,
  64. };
  65. }
  66. }
  67. if (!isset(self::LEVELS[$minLevel])) {
  68. throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $minLevel));
  69. }
  70. $this->minLevelIndex = self::LEVELS[$minLevel];
  71. $this->formatter = null !== $formatter ? $formatter(...) : $this->format(...);
  72. if ($output && false === $this->handle = \is_string($output) ? @fopen($output, 'a') : $output) {
  73. throw new InvalidArgumentException(\sprintf('Unable to open "%s".', $output));
  74. }
  75. $this->debug = $debug;
  76. }
  77. public function enableDebug(): void
  78. {
  79. $this->debug = true;
  80. }
  81. public function log($level, $message, array $context = []): void
  82. {
  83. if (!isset(self::LEVELS[$level])) {
  84. throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $level));
  85. }
  86. if (self::LEVELS[$level] < $this->minLevelIndex) {
  87. return;
  88. }
  89. $formatter = $this->formatter;
  90. if ($this->handle) {
  91. @fwrite($this->handle, $formatter($level, $message, $context).\PHP_EOL);
  92. } else {
  93. error_log($formatter($level, $message, $context, false));
  94. }
  95. if ($this->debug && $this->requestStack) {
  96. $this->record($level, $message, $context);
  97. }
  98. }
  99. public function getLogs(?Request $request = null): array
  100. {
  101. if ($request) {
  102. return $this->logs[spl_object_id($request)] ?? [];
  103. }
  104. return array_merge(...array_values($this->logs));
  105. }
  106. public function countErrors(?Request $request = null): int
  107. {
  108. if ($request) {
  109. return $this->errorCount[spl_object_id($request)] ?? 0;
  110. }
  111. return array_sum($this->errorCount);
  112. }
  113. public function clear(): void
  114. {
  115. $this->logs = [];
  116. $this->errorCount = [];
  117. }
  118. private function format(string $level, string $message, array $context, bool $prefixDate = true): string
  119. {
  120. if (str_contains($message, '{')) {
  121. $replacements = [];
  122. foreach ($context as $key => $val) {
  123. if (null === $val || \is_scalar($val) || $val instanceof \Stringable) {
  124. $replacements["{{$key}}"] = $val;
  125. } elseif ($val instanceof \DateTimeInterface) {
  126. $replacements["{{$key}}"] = $val->format(\DateTimeInterface::RFC3339);
  127. } elseif (\is_object($val)) {
  128. $replacements["{{$key}}"] = '[object '.$val::class.']';
  129. } else {
  130. $replacements["{{$key}}"] = '['.\gettype($val).']';
  131. }
  132. }
  133. $message = strtr($message, $replacements);
  134. }
  135. $log = \sprintf('[%s] %s', $level, $message);
  136. if ($prefixDate) {
  137. $log = date(\DateTimeInterface::RFC3339).' '.$log;
  138. }
  139. return $log;
  140. }
  141. private function record($level, $message, array $context): void
  142. {
  143. $request = $this->requestStack->getCurrentRequest();
  144. $key = $request ? spl_object_id($request) : '';
  145. $this->logs[$key][] = [
  146. 'channel' => null,
  147. 'context' => $context,
  148. 'message' => $message,
  149. 'priority' => self::PRIORITIES[$level],
  150. 'priorityName' => $level,
  151. 'timestamp' => time(),
  152. 'timestamp_rfc3339' => date(\DATE_RFC3339_EXTENDED),
  153. ];
  154. $this->errorCount[$key] ??= 0;
  155. switch ($level) {
  156. case LogLevel::ERROR:
  157. case LogLevel::CRITICAL:
  158. case LogLevel::ALERT:
  159. case LogLevel::EMERGENCY:
  160. ++$this->errorCount[$key];
  161. }
  162. }
  163. }