4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpKernel\Log;
14 use Psr\Log\AbstractLogger;
15 use Psr\Log\InvalidArgumentException;
19 * Minimalist PSR-3 logger designed to write in stderr or any other stream.
21 * @author Kévin Dunglas <dunglas@gmail.com>
23 class Logger extends AbstractLogger
25 private static $levels = array(
28 LogLevel::NOTICE => 2,
29 LogLevel::WARNING => 3,
31 LogLevel::CRITICAL => 5,
33 LogLevel::EMERGENCY => 7,
36 private $minLevelIndex;
40 public function __construct($minLevel = null, $output = 'php://stderr', callable $formatter = null)
42 if (null === $minLevel) {
43 $minLevel = LogLevel::WARNING;
45 if (isset($_ENV['SHELL_VERBOSITY']) || isset($_SERVER['SHELL_VERBOSITY'])) {
46 switch ((int) (isset($_ENV['SHELL_VERBOSITY']) ? $_ENV['SHELL_VERBOSITY'] : $_SERVER['SHELL_VERBOSITY'])) {
47 case -1: $minLevel = LogLevel::ERROR; break;
48 case 1: $minLevel = LogLevel::NOTICE; break;
49 case 2: $minLevel = LogLevel::INFO; break;
50 case 3: $minLevel = LogLevel::DEBUG; break;
55 if (!isset(self::$levels[$minLevel])) {
56 throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $minLevel));
59 $this->minLevelIndex = self::$levels[$minLevel];
60 $this->formatter = $formatter ?: array($this, 'format');
61 if (false === $this->handle = \is_resource($output) ? $output : @fopen($output, 'a')) {
62 throw new InvalidArgumentException(sprintf('Unable to open "%s".', $output));
69 public function log($level, $message, array $context = array())
71 if (!isset(self::$levels[$level])) {
72 throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
75 if (self::$levels[$level] < $this->minLevelIndex) {
79 $formatter = $this->formatter;
80 fwrite($this->handle, $formatter($level, $message, $context));
84 * @param string $level
85 * @param string $message
86 * @param array $context
90 private function format($level, $message, array $context)
92 if (false !== strpos($message, '{')) {
93 $replacements = array();
94 foreach ($context as $key => $val) {
95 if (null === $val || is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
96 $replacements["{{$key}}"] = $val;
97 } elseif ($val instanceof \DateTimeInterface) {
98 $replacements["{{$key}}"] = $val->format(\DateTime::RFC3339);
99 } elseif (\is_object($val)) {
100 $replacements["{{$key}}"] = '[object '.\get_class($val).']';
102 $replacements["{{$key}}"] = '['.\gettype($val).']';
106 $message = strtr($message, $replacements);
109 return sprintf('%s [%s] %s', date(\DateTime::RFC3339), $level, $message).\PHP_EOL;