Logger.php 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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;
  45. break;
  46. case 1: $minLevel = LogLevel::NOTICE;
  47. break;
  48. case 2: $minLevel = LogLevel::INFO;
  49. break;
  50. case 3: $minLevel = LogLevel::DEBUG;
  51. break;
  52. }
  53. }
  54. }
  55. if (!isset(self::LEVELS[$minLevel])) {
  56. throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel));
  57. }
  58. $this->minLevelIndex = self::LEVELS[$minLevel];
  59. $this->formatter = $formatter ?: [$this, 'format'];
  60. if ($output && false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) {
  61. throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output));
  62. }
  63. }
  64. /**
  65. * {@inheritdoc}
  66. *
  67. * @return void
  68. */
  69. public function log($level, $message, array $context = [])
  70. {
  71. if (!isset(self::LEVELS[$level])) {
  72. throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
  73. }
  74. if (self::LEVELS[$level] < $this->minLevelIndex) {
  75. return;
  76. }
  77. $formatter = $this->formatter;
  78. if ($this->handle) {
  79. @fwrite($this->handle, $formatter($level, $message, $context).\PHP_EOL);
  80. } else {
  81. error_log($formatter($level, $message, $context, false));
  82. }
  83. }
  84. private function format(string $level, string $message, array $context, bool $prefixDate = true): string
  85. {
  86. if (str_contains($message, '{')) {
  87. $replacements = [];
  88. foreach ($context as $key => $val) {
  89. if (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
  90. $replacements["{{$key}}"] = $val;
  91. } elseif ($val instanceof \DateTimeInterface) {
  92. $replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
  93. } elseif (\is_object($val)) {
  94. $replacements["{{$key}}"] = '[object '.\get_class($val).']';
  95. } else {
  96. $replacements["{{$key}}"] = '['.\gettype($val).']';
  97. }
  98. }
  99. $message = strtr($message, $replacements);
  100. }
  101. $log = sprintf('[%s] %s', $level, $message);
  102. if ($prefixDate) {
  103. $log = date(\DateTime::RFC3339).' '.$log;
  104. }
  105. return $log;
  106. }
  107. }