1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Sentry\Tracing; |
6
|
|
|
|
7
|
|
|
use Psr\Log\LoggerInterface; |
8
|
|
|
use Sentry\SentrySdk; |
9
|
|
|
use Sentry\Tracing\SpanContext; |
10
|
|
|
use Sentry\Tracing\TransactionContext; |
11
|
|
|
use Yiisoft\Yii\Console\Event\ApplicationShutdown; |
12
|
|
|
|
13
|
|
|
final class SentryConsoleTransactionAdapter |
14
|
|
|
{ |
15
|
|
|
public function __construct(private LoggerInterface $logger, private SentryTraceConsoleListener $consoleListener) |
16
|
|
|
{ |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function begin(?string $sentryTraceString = null): self |
20
|
|
|
{ |
21
|
|
|
$hub = SentrySdk::getCurrentHub(); |
22
|
|
|
if ($sentryTraceString) { |
23
|
|
|
$context = TransactionContext::fromSentryTrace($sentryTraceString); |
24
|
|
|
} else { |
25
|
|
|
$context = new TransactionContext(); |
26
|
|
|
} |
27
|
|
|
$context->setOp('console sub task'); |
28
|
|
|
|
29
|
|
|
$context->setStartTimestamp(microtime(true)); |
|
|
|
|
30
|
|
|
|
31
|
|
|
$transaction = $hub->startTransaction($context); |
32
|
|
|
$transaction->setName('undefined command'); |
33
|
|
|
$hub->setSpan($transaction); |
34
|
|
|
$this->consoleListener->setTransaction($transaction); |
35
|
|
|
|
36
|
|
|
$appContextStart = new SpanContext(); |
37
|
|
|
$appContextStart->setOp('handle'); |
38
|
|
|
$appContextStart->setStartTimestamp(microtime(true)); |
39
|
|
|
$appSpan = $transaction->startChild($appContextStart); |
40
|
|
|
SentrySdk::getCurrentHub()->setSpan($appSpan); |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function setName(string $name): self |
46
|
|
|
{ |
47
|
|
|
SentrySdk::getCurrentHub()->getTransaction()?->setName($name); |
48
|
|
|
|
49
|
|
|
return $this; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param array<string, mixed> $data |
54
|
|
|
* |
55
|
|
|
* @return $this |
56
|
|
|
*/ |
57
|
|
|
public function setData(array $data): self |
58
|
|
|
{ |
59
|
|
|
SentrySdk::getCurrentHub()->getTransaction()?->setData($data); |
60
|
|
|
|
61
|
|
|
return $this; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function commit(): ?string |
65
|
|
|
{ |
66
|
|
|
$this->logger->info('sentry force commit'); |
67
|
|
|
$sentryTraceString = SentrySdk::getCurrentHub()->getSpan()?->toTraceparent(); |
68
|
|
|
if (method_exists($this->logger, 'flush') && SentrySdk::getCurrentHub()->getTransaction() !== null) { |
69
|
|
|
$this->logger->flush(true); |
|
|
|
|
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$this->consoleListener->listenCommandTerminate(null); |
73
|
|
|
$this->consoleListener->listenShutdown(new ApplicationShutdown(0)); |
74
|
|
|
$this->consoleListener->setTransaction(null); |
75
|
|
|
|
76
|
|
|
return $sentryTraceString; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|