Logger.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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. $minLevel ??= match ((int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'] ?? 0)) {
  56. -1 => LogLevel::ERROR,
  57. 1 => LogLevel::NOTICE,
  58. 2 => LogLevel::INFO,
  59. 3 => LogLevel::DEBUG,
  60. default => null === $output || 'php://stdout' === $output || 'php://stderr' === $output ? LogLevel::ERROR : LogLevel::WARNING,
  61. };
  62. if (!isset(self::LEVELS[$minLevel])) {
  63. throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $minLevel));
  64. }
  65. $this->minLevelIndex = self::LEVELS[$minLevel];
  66. $this->formatter = null !== $formatter ? $formatter(...) : $this->format(...);
  67. if ($output && false === $this->handle = \is_string($output) ? @fopen($output, 'a') : $output) {
  68. throw new InvalidArgumentException(\sprintf('Unable to open "%s".', $output));
  69. }
  70. $this->debug = $debug;
  71. }
  72. public function enableDebug(): void
  73. {
  74. $this->debug = true;
  75. }
  76. public function log($level, $message, array $context = []): void
  77. {
  78. if (!isset(self::LEVELS[$level])) {
  79. throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $level));
  80. }
  81. if (self::LEVELS[$level] < $this->minLevelIndex) {
  82. return;
  83. }
  84. $formatter = $this->formatter;
  85. if ($this->handle) {
  86. @fwrite($this->handle, $formatter($level, $message, $context).\PHP_EOL);
  87. } else {
  88. error_log($formatter($level, $message, $context, false));
  89. }
  90. if ($this->debug && $this->requestStack) {
  91. $this->record($level, $message, $context);
  92. }
  93. }
  94. public function getLogs(?Request $request = null): array
  95. {
  96. if ($request) {
  97. return $this->logs[spl_object_id($request)] ?? [];
  98. }
  99. return array_merge(...array_values($this->logs));
  100. }
  101. public function countErrors(?Request $request = null): int
  102. {
  103. if ($request) {
  104. return $this->errorCount[spl_object_id($request)] ?? 0;
  105. }
  106. return array_sum($this->errorCount);
  107. }
  108. public function clear(): void
  109. {
  110. $this->logs = [];
  111. $this->errorCount = [];
  112. }
  113. private function format(string $level, string $message, array $context, bool $prefixDate = true): string
  114. {
  115. if (str_contains($message, '{')) {
  116. $replacements = [];
  117. foreach ($context as $key => $val) {
  118. if (null === $val || \is_scalar($val) || $val instanceof \Stringable) {
  119. $replacements["{{$key}}"] = $val;
  120. } elseif ($val instanceof \DateTimeInterface) {
  121. $replacements["{{$key}}"] = $val->format(\DateTimeInterface::RFC3339);
  122. } elseif (\is_object($val)) {
  123. $replacements["{{$key}}"] = '[object '.$val::class.']';
  124. } else {
  125. $replacements["{{$key}}"] = '['.\gettype($val).']';
  126. }
  127. }
  128. $message = strtr($message, $replacements);
  129. }
  130. $log = \sprintf('[%s] %s', $level, $message);
  131. if ($prefixDate) {
  132. $log = date(\DateTimeInterface::RFC3339).' '.$log;
  133. }
  134. return $log;
  135. }
  136. private function record($level, $message, array $context): void
  137. {
  138. $request = $this->requestStack->getCurrentRequest();
  139. $key = $request ? spl_object_id($request) : '';
  140. $this->logs[$key][] = [
  141. 'channel' => null,
  142. 'context' => $context,
  143. 'message' => $message,
  144. 'priority' => self::PRIORITIES[$level],
  145. 'priorityName' => $level,
  146. 'timestamp' => time(),
  147. 'timestamp_rfc3339' => date(\DATE_RFC3339_EXTENDED),
  148. ];
  149. $this->errorCount[$key] ??= 0;
  150. switch ($level) {
  151. case LogLevel::ERROR:
  152. case LogLevel::CRITICAL:
  153. case LogLevel::ALERT:
  154. case LogLevel::EMERGENCY:
  155. ++$this->errorCount[$key];
  156. }
  157. }
  158. }