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\Console\EventListener;
14 use Psr\Log\LoggerInterface;
15 use Symfony\Component\Console\ConsoleEvents;
16 use Symfony\Component\Console\Event\ConsoleErrorEvent;
17 use Symfony\Component\Console\Event\ConsoleEvent;
18 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
19 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
22 * @author James Halsall <james.t.halsall@googlemail.com>
23 * @author Robin Chalas <robin.chalas@gmail.com>
25 class ErrorListener implements EventSubscriberInterface
29 public function __construct(LoggerInterface $logger = null)
31 $this->logger = $logger;
34 public function onConsoleError(ConsoleErrorEvent $event)
36 if (null === $this->logger) {
40 $error = $event->getError();
42 if (!$inputString = $this->getInputString($event)) {
43 return $this->logger->error('An error occurred while using the console. Message: "{message}"', array('exception' => $error, 'message' => $error->getMessage()));
46 $this->logger->error('Error thrown while running command "{command}". Message: "{message}"', array('exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()));
49 public function onConsoleTerminate(ConsoleTerminateEvent $event)
51 if (null === $this->logger) {
55 $exitCode = $event->getExitCode();
57 if (0 === $exitCode) {
61 if (!$inputString = $this->getInputString($event)) {
62 return $this->logger->debug('The console exited with code "{code}"', array('code' => $exitCode));
65 $this->logger->debug('Command "{command}" exited with code "{code}"', array('command' => $inputString, 'code' => $exitCode));
68 public static function getSubscribedEvents()
71 ConsoleEvents::ERROR => array('onConsoleError', -128),
72 ConsoleEvents::TERMINATE => array('onConsoleTerminate', -128),
76 private static function getInputString(ConsoleEvent $event)
78 $commandName = $event->getCommand() ? $event->getCommand()->getName() : null;
79 $input = $event->getInput();
81 if (method_exists($input, '__toString')) {
83 return str_replace(array("'$commandName'", "\"$commandName\""), $commandName, (string) $input);
86 return (string) $input;