|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Jaeger\Symfony\Bridge; |
| 5 | + |
| 6 | +use Jaeger\Span\SpanManagerInterface; |
| 7 | +use Jaeger\Tag\ErrorTag; |
| 8 | +use Jaeger\Tracer\TracerInterface; |
| 9 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 10 | +use Symfony\Component\HttpKernel\Event\ExceptionEvent; |
| 11 | +use Symfony\Component\HttpKernel\Event\RequestEvent; |
| 12 | +use Symfony\Component\HttpKernel\Event\TerminateEvent; |
| 13 | +use Symfony\Component\HttpKernel\HttpKernelInterface; |
| 14 | + |
| 15 | +class ExceptionListener implements EventSubscriberInterface |
| 16 | +{ |
| 17 | + private $tracer; |
| 18 | + private $spanManager; |
| 19 | + private $globalSpanHandler; |
| 20 | + private $exceptionExist; |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + TracerInterface $tracer, |
| 24 | + SpanManagerInterface $spanManager, |
| 25 | + GlobalSpanHandler $globalSpanHandler |
| 26 | + ) { |
| 27 | + $this->tracer = $tracer; |
| 28 | + $this->spanManager = $spanManager; |
| 29 | + $this->globalSpanHandler = $globalSpanHandler; |
| 30 | + $this->exceptionExist = false; |
| 31 | + } |
| 32 | + |
| 33 | + public static function getSubscribedEvents(): array |
| 34 | + { |
| 35 | + return [ |
| 36 | + ExceptionEvent::class => ['onKernelException', 0], |
| 37 | + RequestEvent::class => ['onRequest', 28], |
| 38 | + TerminateEvent::class => ['onTerminate', 4097], |
| 39 | + ]; |
| 40 | + } |
| 41 | + |
| 42 | + public function onKernelException(ExceptionEvent $event): void |
| 43 | + { |
| 44 | + if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) { |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + $span = $this->spanManager->getSpan(); |
| 49 | + |
| 50 | + if (null !== $span) { |
| 51 | + $span->addTag(new ErrorTag()); |
| 52 | + $this->exceptionExist = true; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public function onRequest(RequestEvent $event): void |
| 57 | + { |
| 58 | + if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + if ($this->exceptionExist) { |
| 63 | + $span = $this->spanManager->getSpan(); |
| 64 | + $span->addTag(new ErrorTag()); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + public function onTerminate(): void |
| 69 | + { |
| 70 | + if ($this->exceptionExist) { |
| 71 | + $this->globalSpanHandler->addTag(new ErrorTag()); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments