Logger.php 3.8 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\HttpKernel\Log;
  11. use Psr\Log\AbstractLogger;
  12. use Psr\Log\InvalidArgumentException;
  13. use Psr\Log\LogLevel;
  14. /**
  15. * Minimalist PSR-3 logger designed to write in stderr or any other stream.
  16. *
  17. * @author Kévin Dunglas <dunglas@gmail.com>
  18. */
  19. class Logger extends AbstractLogger
  20. {
  21. private const LEVELS = [
  22. LogLevel::DEBUG => 0,
  23. LogLevel::INFO => 1,
  24. LogLevel::NOTICE => 2,
  25. LogLevel::WARNING => 3,
  26. LogLevel::ERROR => 4,
  27. LogLevel::CRITICAL => 5,
  28. LogLevel::ALERT => 6,
  29. LogLevel::EMERGENCY => 7,
  30. ];
  31. private $minLevelIndex;
  32. private $formatter;
  33. /** @var resource|null */
  34. private $handle;
  35. /**
  36. * @param string|resource|null $output
  37. */
  38. public function __construct(string $minLevel = null, $output = null, callable $formatter = null)
  39. {
  40. if (null === $minLevel) {
  41. $minLevel = null === $output || 'php://stdout' === $output || 'php://stderr' === $output ? LogLevel::ERROR : LogLevel::WARNING;
  42. if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
  43. switch ((int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'])) {
  44. case -1: $minLevel = LogLevel::ERROR; break;
  45. case 1: $minLevel = LogLevel::NOTICE; break;
  46. case 2: $minLevel = LogLevel::INFO; break;
  47. case 3: $minLevel = LogLevel::DEBUG; break;
  48. }
  49. }
  50. }
  51. if (!isset(self::LEVELS[$minLevel])) {
  52. throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel));
  53. }
  54. $this->minLevelIndex = self::LEVELS[$minLevel];
  55. $this->formatter = $formatter ?: [$this, 'format'];
  56. if ($output && false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) {
  57. throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output));
  58. }
  59. }
  60. /**
  61. * {@inheritdoc}
  62. *
  63. * @return void
  64. */
  65. public function log($level, $message, array $context = [])
  66. {
  67. if (!isset(self::LEVELS[$level])) {
  68. throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
  69. }
  70. if (self::LEVELS[$level] < $this->minLevelIndex) {
  71. return;
  72. }
  73. $formatter = $this->formatter;
  74. if ($this->handle) {
  75. @fwrite($this->handle, $formatter($level, $message, $context));
  76. } else {
  77. error_log($formatter($level, $message, $context, false));
  78. }
  79. }
  80. private function format(string $level, string $message, array $context, bool $prefixDate = true): string
  81. {
  82. if (str_contains($message, '{')) {
  83. $replacements = [];
  84. foreach ($context as $key => $val) {
  85. if (null === $val || is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
  86. $replacements["{{$key}}"] = $val;
  87. } elseif ($val instanceof \DateTimeInterface) {
  88. $replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
  89. } elseif (\is_object($val)) {
  90. $replacements["{{$key}}"] = '[object '.\get_class($val).']';
  91. } else {
  92. $replacements["{{$key}}"] = '['.\gettype($val).']';
  93. }
  94. }
  95. $message = strtr($message, $replacements);
  96. }
  97. $log = sprintf('[%s] %s', $level, $message).\PHP_EOL;
  98. if ($prefixDate) {
  99. $log = date(\DateTime::RFC3339).' '.$log;
  100. }
  101. return $log;
  102. }
  103. }