vendor/sentry/sentry-symfony/src/EventListener/ConsoleCommandListener.php line 46

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sentry\SentryBundle\EventListener;
  4. use Sentry\State\HubInterface;
  5. use Sentry\State\Scope;
  6. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  7. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  8. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  9. /**
  10.  * This listener handles all errors thrown while running a console command and
  11.  * logs them to Sentry.
  12.  */
  13. final class ConsoleCommandListener
  14. {
  15.     /**
  16.      * @var HubInterface The current hub
  17.      */
  18.     private $hub;
  19.     /**
  20.      * @var bool Whether to capture console errors
  21.      */
  22.     private $captureErrors;
  23.     /**
  24.      * Constructor.
  25.      *
  26.      * @param HubInterface $hub           The current hub
  27.      * @param bool         $captureErrors Whether to capture console errors
  28.      */
  29.     public function __construct(HubInterface $hubbool $captureErrors true)
  30.     {
  31.         $this->hub $hub;
  32.         $this->captureErrors $captureErrors;
  33.     }
  34.     /**
  35.      * Handles the execution of a console command by pushing a new {@see Scope}.
  36.      *
  37.      * @param ConsoleCommandEvent $event The event
  38.      */
  39.     public function handleConsoleCommandEvent(ConsoleCommandEvent $event): void
  40.     {
  41.         $scope $this->hub->pushScope();
  42.         $command $event->getCommand();
  43.         if (null !== $command && null !== $command->getName()) {
  44.             $scope->setTag('console.command'$command->getName());
  45.         }
  46.     }
  47.     /**
  48.      * Handles the termination of a console command by popping the {@see Scope}.
  49.      *
  50.      * @param ConsoleTerminateEvent $event The event
  51.      */
  52.     public function handleConsoleTerminateEvent(ConsoleTerminateEvent $event): void
  53.     {
  54.         $this->hub->popScope();
  55.     }
  56.     /**
  57.      * Handles an error that happened while running a console command.
  58.      *
  59.      * @param ConsoleErrorEvent $event The event
  60.      */
  61.     public function handleConsoleErrorEvent(ConsoleErrorEvent $event): void
  62.     {
  63.         $this->hub->configureScope(function (Scope $scope) use ($event): void {
  64.             $scope->setTag('console.command.exit_code', (string) $event->getExitCode());
  65.             if ($this->captureErrors) {
  66.                 $this->hub->captureException($event->getError());
  67.             }
  68.         });
  69.     }
  70. }