ConsoleLogger.php 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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\Console\Logger;
  11. use Psr\Log\AbstractLogger;
  12. use Psr\Log\InvalidArgumentException;
  13. use Psr\Log\LogLevel;
  14. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. /**
  17. * PSR-3 compliant console logger.
  18. *
  19. * @author Kévin Dunglas <dunglas@gmail.com>
  20. *
  21. * @see https://www.php-fig.org/psr/psr-3/
  22. */
  23. class ConsoleLogger extends AbstractLogger
  24. {
  25. public const INFO = 'info';
  26. public const ERROR = 'error';
  27. private array $verbosityLevelMap = [
  28. LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
  29. LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
  30. LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
  31. LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL,
  32. LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL,
  33. LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE,
  34. LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE,
  35. LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG,
  36. ];
  37. private array $formatLevelMap = [
  38. LogLevel::EMERGENCY => self::ERROR,
  39. LogLevel::ALERT => self::ERROR,
  40. LogLevel::CRITICAL => self::ERROR,
  41. LogLevel::ERROR => self::ERROR,
  42. LogLevel::WARNING => self::INFO,
  43. LogLevel::NOTICE => self::INFO,
  44. LogLevel::INFO => self::INFO,
  45. LogLevel::DEBUG => self::INFO,
  46. ];
  47. private bool $errored = false;
  48. public function __construct(
  49. private OutputInterface $output,
  50. array $verbosityLevelMap = [],
  51. array $formatLevelMap = [],
  52. ) {
  53. $this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap;
  54. $this->formatLevelMap = $formatLevelMap + $this->formatLevelMap;
  55. }
  56. public function log($level, $message, array $context = []): void
  57. {
  58. if (!isset($this->verbosityLevelMap[$level])) {
  59. throw new InvalidArgumentException(\sprintf('The log level "%s" does not exist.', $level));
  60. }
  61. $output = $this->output;
  62. // Write to the error output if necessary and available
  63. if (self::ERROR === $this->formatLevelMap[$level]) {
  64. if ($this->output instanceof ConsoleOutputInterface) {
  65. $output = $output->getErrorOutput();
  66. }
  67. $this->errored = true;
  68. }
  69. // the if condition check isn't necessary -- it's the same one that $output will do internally anyway.
  70. // We only do it for efficiency here as the message formatting is relatively expensive.
  71. if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) {
  72. $output->writeln(\sprintf('<%1$s>[%2$s] %3$s</%1$s>', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)), $this->verbosityLevelMap[$level]);
  73. }
  74. }
  75. /**
  76. * Returns true when any messages have been logged at error levels.
  77. */
  78. public function hasErrored(): bool
  79. {
  80. return $this->errored;
  81. }
  82. /**
  83. * Interpolates context values into the message placeholders.
  84. *
  85. * @author PHP Framework Interoperability Group
  86. */
  87. private function interpolate(string $message, array $context): string
  88. {
  89. if (!str_contains($message, '{')) {
  90. return $message;
  91. }
  92. $replacements = [];
  93. foreach ($context as $key => $val) {
  94. if (null === $val || \is_scalar($val) || $val instanceof \Stringable) {
  95. $replacements["{{$key}}"] = $val;
  96. } elseif ($val instanceof \DateTimeInterface) {
  97. $replacements["{{$key}}"] = $val->format(\DateTimeInterface::RFC3339);
  98. } elseif (\is_object($val)) {
  99. $replacements["{{$key}}"] = '[object '.$val::class.']';
  100. } else {
  101. $replacements["{{$key}}"] = '['.\gettype($val).']';
  102. }
  103. }
  104. return strtr($message, $replacements);
  105. }
  106. }