vendor/sentry/sentry-symfony/src/EventListener/ConsoleListener.php line 72

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