33
44namespace PcComponentes \ElasticAPM \Symfony \Component \Console ;
55
6+ use Symfony \Component \Console \Command \Command ;
67use Symfony \Component \Console \ConsoleEvents ;
78use Symfony \Component \Console \Event \ConsoleCommandEvent ;
89use Symfony \Component \Console \Event \ConsoleErrorEvent ;
910use Symfony \Component \Console \Event \ConsoleTerminateEvent ;
1011use Symfony \Component \EventDispatcher \EventSubscriberInterface ;
1112use ZoiloMora \ElasticAPM \ElasticApmTracer ;
12- use ZoiloMora \ElasticAPM \Events \Transaction \Transaction ;
1313
1414final class EventSubscriber implements EventSubscriberInterface
1515{
1616 private ElasticApmTracer $ elasticApmTracer ;
1717
18- private Transaction $ transaction ;
18+ private array $ transactions ;
19+ private array $ spans ;
1920
2021 public function __construct (ElasticApmTracer $ elasticApmTracer )
2122 {
2223 $ this ->elasticApmTracer = $ elasticApmTracer ;
24+ $ this ->transactions = [];
25+ $ this ->spans = [];
2326 }
2427
2528 public static function getSubscribedEvents (): array
@@ -34,19 +37,39 @@ public static function getSubscribedEvents(): array
3437 public function onConsoleCommandEvent (ConsoleCommandEvent $ event ): void
3538 {
3639 $ command = $ event ->getCommand ();
40+ $ key = $ this ->transactionKey ($ command );
3741
38- $ this ->transaction = $ this ->elasticApmTracer ->startTransaction (
42+ if (0 !== \count ($ this ->transactions )) {
43+ $ this ->spans [$ key ] = $ this ->elasticApmTracer ->startSpan (
44+ $ command ->getName (),
45+ 'console ' ,
46+ );
47+ }
48+
49+ $ this ->transactions [$ key ] = $ this ->elasticApmTracer ->startTransaction (
3950 $ command ->getName (),
4051 'console ' ,
4152 );
4253 }
4354
4455 public function onConsoleTerminateEvent (ConsoleTerminateEvent $ event ): void
4556 {
46- $ this ->transaction ->stop (
57+ $ key = $ this ->transactionKey (
58+ $ event ->getCommand (),
59+ );
60+
61+ $ this ->transactions [$ key ]->stop (
4762 (string ) $ event ->getExitCode (),
4863 );
4964
65+ if (true === \array_key_exists ($ key , $ this ->spans )) {
66+ $ this ->spans [$ key ]->stop ();
67+ }
68+
69+ if (\array_key_first ($ this ->transactions ) !== $ key ) {
70+ return ;
71+ }
72+
5073 $ this ->elasticApmTracer ->flush ();
5174 }
5275
@@ -55,9 +78,10 @@ public function onConsoleErrorEvent(ConsoleErrorEvent $event): void
5578 $ this ->elasticApmTracer ->captureException (
5679 $ event ->getError (),
5780 );
81+ }
5882
59- $ this -> transaction -> stop (
60- ( string ) $ event -> getExitCode (),
61- );
83+ private function transactionKey ( Command $ command ): int
84+ {
85+ return \spl_object_id ( $ command );
6286 }
6387}
0 commit comments