/
EventHandler.php
120 lines (104 loc) · 2.97 KB
/
EventHandler.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace Sentry\Laravel\Tracing;
use Exception;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Events\QueryExecuted;
use RuntimeException;
use Sentry\Laravel\Integration;
use Sentry\Tracing\SpanContext;
class EventHandler
{
/**
* Map event handlers to events.
*
* @var array
*/
protected static $eventHandlerMap = [
'illuminate.query' => 'query', // Until Laravel 5.1
QueryExecuted::class => 'queryExecuted', // Since Laravel 5.2
];
/**
* The Laravel event dispatcher.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
private $events;
/**
* EventHandler constructor.
*
* @param \Illuminate\Contracts\Events\Dispatcher $events
*/
public function __construct(Dispatcher $events)
{
$this->events = $events;
}
/**
* Attach all event handlers.
*/
public function subscribe(): void
{
foreach (static::$eventHandlerMap as $eventName => $handler) {
$this->events->listen($eventName, [$this, $handler]);
}
}
/**
* Pass through the event and capture any errors.
*
* @param string $method
* @param array $arguments
*/
public function __call($method, $arguments)
{
$handlerMethod = $handlerMethod = "{$method}Handler";
if (!method_exists($this, $handlerMethod)) {
throw new RuntimeException("Missing tracing event handler: {$handlerMethod}");
}
$parentSpan = Integration::currentTracingSpan();
// If there is no tracing span active there is no need to handle the event
if ($parentSpan === null) {
return;
}
try {
call_user_func_array([$this, $handlerMethod], $arguments);
} catch (Exception $exception) {
// Ignore
}
}
/**
* Until Laravel 5.1
*
* @param string $query
* @param array $bindings
* @param int $time
* @param string $connectionName
*/
protected function queryHandler($query, $bindings, $time, $connectionName): void
{
$this->recordQuerySpan($query, $time);
}
/**
* Since Laravel 5.2
*
* @param \Illuminate\Database\Events\QueryExecuted $query
*/
protected function queryExecutedHandler(QueryExecuted $query): void
{
$this->recordQuerySpan($query->sql, $query->time);
}
/**
* Helper to add an query breadcrumb.
*
* @param string $query
* @param float|null $time
*/
private function recordQuerySpan($query, $time): void
{
$parentSpan = Integration::currentTracingSpan();
$context = new SpanContext();
$context->setOp('sql.query');
$context->setDescription($query);
$context->setStartTimestamp(microtime(true) - $time / 1000);
$context->setEndTimestamp($context->getStartTimestamp() + $time / 1000);
$parentSpan->startChild($context);
}
}