vendor/sentry/sentry-symfony/src/EventListener/TracingConsoleListener.php line 70

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Sentry\SentryBundle\EventListener;
  4. use Sentry\State\HubInterface;
  5. use Sentry\Tracing\Span;
  6. use Sentry\Tracing\SpanContext;
  7. use Sentry\Tracing\Transaction;
  8. use Sentry\Tracing\TransactionContext;
  9. use Symfony\Component\Console\Command\Command;
  10. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  11. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  12. /**
  13.  * This listener either starts a {@see Transaction} or a child {@see Span} when
  14.  * a console command is executed to allow measuring the application performances.
  15.  */
  16. final class TracingConsoleListener
  17. {
  18.     /**
  19.      * @var HubInterface The current hub
  20.      */
  21.     private $hub;
  22.     /**
  23.      * Constructor.
  24.      *
  25.      * @param HubInterface $hub The current hub
  26.      */
  27.     public function __construct(HubInterface $hub)
  28.     {
  29.         $this->hub $hub;
  30.     }
  31.     /**
  32.      * Handles the execution of a console command by starting a new {@see Transaction}
  33.      * if it doesn't exists, or a child {@see Span} if it does.
  34.      *
  35.      * @param ConsoleCommandEvent $event The event
  36.      */
  37.     public function handleConsoleCommandEvent(ConsoleCommandEvent $event): void
  38.     {
  39.         $currentSpan $this->hub->getSpan();
  40.         if (null === $currentSpan) {
  41.             $transactionContext = new TransactionContext();
  42.             $transactionContext->setOp('console.command');
  43.             $transactionContext->setName($this->getSpanName($event->getCommand()));
  44.             $span $this->hub->startTransaction($transactionContext);
  45.         } else {
  46.             $spanContext = new SpanContext();
  47.             $spanContext->setOp('console.command');
  48.             $spanContext->setDescription($this->getSpanName($event->getCommand()));
  49.             $span $currentSpan->startChild($spanContext);
  50.         }
  51.         $this->hub->setSpan($span);
  52.     }
  53.     /**
  54.      * Handles the termination of a console command by stopping the active {@see Span}
  55.      * or {@see Transaction}.
  56.      *
  57.      * @param ConsoleTerminateEvent $event The event
  58.      */
  59.     public function handleConsoleTerminateEvent(ConsoleTerminateEvent $event): void
  60.     {
  61.         $span $this->hub->getSpan();
  62.         if (null !== $span) {
  63.             $span->finish();
  64.         }
  65.     }
  66.     private function getSpanName(?Command $command): string
  67.     {
  68.         if (null === $command || null === $command->getName()) {
  69.             return '<unnamed command>';
  70.         }
  71.         return $command->getName();
  72.     }
  73. }