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
|
|
|
|
12
|
|
|
class SentryWebTransactionAdapter |
13
|
|
|
{ |
14
|
|
|
public function __construct(private LoggerInterface $logger, private SentryTraceMiddleware $middleware) |
15
|
|
|
{ |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function begin(?string $sentryTraceString = null, string $baggage = ''): self |
19
|
|
|
{ |
20
|
|
|
$hub = SentrySdk::getCurrentHub(); |
21
|
|
|
if ($sentryTraceString) { |
22
|
|
|
$context = TransactionContext::fromHeaders($sentryTraceString, $baggage); |
23
|
|
|
} else { |
24
|
|
|
$context = new TransactionContext(); |
25
|
|
|
} |
26
|
|
|
$context->setOp('web subtask'); |
27
|
|
|
|
28
|
|
|
$context->setStartTimestamp(microtime(true)); |
|
|
|
|
29
|
|
|
|
30
|
|
|
$transaction = $hub->startTransaction($context); |
31
|
|
|
$transaction->setName('undefined action'); |
32
|
|
|
$hub->setSpan($transaction); |
33
|
|
|
$this->middleware->setTransaction($transaction); |
34
|
|
|
|
35
|
|
|
$appContextStart = new SpanContext(); |
36
|
|
|
$appContextStart->setOp('handle'); |
37
|
|
|
$appContextStart->setStartTimestamp(microtime(true)); |
38
|
|
|
$appSpan = $transaction->startChild($appContextStart); |
39
|
|
|
SentrySdk::getCurrentHub()->setSpan($appSpan); |
40
|
|
|
|
41
|
|
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function setName(string $name): self |
45
|
|
|
{ |
46
|
|
|
SentrySdk::getCurrentHub()->getTransaction()?->setName($name); |
47
|
|
|
|
48
|
|
|
return $this; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function getName(): ?string |
52
|
|
|
{ |
53
|
|
|
return SentrySdk::getCurrentHub()->getTransaction()?->getName(); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param array<string, mixed> $data |
58
|
|
|
* |
59
|
|
|
* @return $this |
60
|
|
|
*/ |
61
|
|
|
public function setData(array $data): self |
62
|
|
|
{ |
63
|
|
|
SentrySdk::getCurrentHub()->getTransaction()?->setData($data); |
64
|
|
|
|
65
|
|
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function commit(): ?string |
69
|
|
|
{ |
70
|
|
|
$this->logger->info('sentry force commit'); |
71
|
|
|
$sentryTraceString = SentrySdk::getCurrentHub()->getSpan()?->toTraceparent(); |
72
|
|
|
if (method_exists($this->logger, 'flush') && SentrySdk::getCurrentHub()->getTransaction() !== null) { |
73
|
|
|
$this->logger->flush(true); |
|
|
|
|
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$this->middleware->terminate(); |
77
|
|
|
|
78
|
|
|
return $sentryTraceString; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|