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