-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathSentryTarget.php
239 lines (212 loc) · 7.13 KB
/
SentryTarget.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
<?php
/**
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace notamedia\sentry;
use Sentry\ClientBuilder;
use Sentry\Event;
use Sentry\EventHint;
use Sentry\Integration\ErrorListenerIntegration;
use Sentry\Integration\ExceptionListenerIntegration;
use Sentry\Integration\FatalErrorListenerIntegration;
use Sentry\Integration\IntegrationInterface;
use Sentry\SentrySdk;
use Sentry\Severity;
use Sentry\State\Scope;
use Throwable;
use Yii;
use yii\helpers\ArrayHelper;
use yii\log\Logger;
use yii\log\Target;
use yii\web\Request;
use yii\web\User;
/**
* SentryTarget records log messages in a Sentry.
*
* @see https://sentry.io
*/
class SentryTarget extends Target
{
/**
* @var string Sentry client key.
*/
public $dsn;
/**
* @var array Options of the \Sentry.
*/
public $clientOptions = [];
/**
* @var bool Write the context information. The default implementation will dump user information, system variables, etc.
*/
public $context = true;
/**
* @var callable Callback function that can modify extra's array
*/
public $extraCallback;
/**
* @inheritDoc
*/
public function __construct($config = [])
{
parent::__construct($config);
$userOptions = array_merge(['dsn' => $this->dsn], $this->clientOptions);
$builder = ClientBuilder::create($userOptions);
$options = $builder->getOptions();
$options->setIntegrations(static function (array $integrations) {
// Remove the default error and fatal exception listeners to let us handle those
return array_filter($integrations, static function (IntegrationInterface $integration): bool {
if ($integration instanceof ErrorListenerIntegration) {
return false;
}
if ($integration instanceof ExceptionListenerIntegration) {
return false;
}
if ($integration instanceof FatalErrorListenerIntegration) {
return false;
}
return true;
});
});
SentrySdk::init()->bindClient($builder->getClient());
}
/**
* @inheritdoc
*/
protected function getContextMessage()
{
return '';
}
/**
* @inheritdoc
*/
public function export()
{
foreach ($this->messages as $message) {
[$text, $level, $category] = $message;
$data = [
'message' => '',
'tags' => ['category' => $category],
'extra' => [],
'userData' => [],
];
$request = Yii::$app->getRequest();
if ($request instanceof Request && $request->getUserIP()) {
$data['userData']['ip_address'] = $request->getUserIP();
}
try {
/** @var User $user */
$user = Yii::$app->has('user', true) ? Yii::$app->get('user', false) : null;
if ($user && ($identity = $user->getIdentity(false))) {
$data['userData']['id'] = $identity->getId();
}
} catch (Throwable $e) {}
\Sentry\withScope(function (Scope $scope) use ($text, $level, $data) {
if (is_array($text)) {
if (isset($text['msg'])) {
$data['message'] = (string)$text['msg'];
unset($text['msg']);
}
if (isset($text['message'])) {
$data['message'] = (string)$text['message'];
unset($text['message']);
}
if (isset($text['tags'])) {
$data['tags'] = ArrayHelper::merge($data['tags'], $text['tags']);
unset($text['tags']);
}
if (isset($text['exception']) && $text['exception'] instanceof Throwable) {
$data['exception'] = $text['exception'];
unset($text['exception']);
}
$data['extra'] = $text;
} else {
$data['message'] = (string) $text;
}
if ($this->context) {
$data['extra']['context'] = parent::getContextMessage();
}
$data = $this->runExtraCallback($text, $data);
$scope->setUser($data['userData']);
foreach ($data['extra'] as $key => $value) {
$scope->setExtra((string) $key, $value);
}
foreach ($data['tags'] as $key => $value) {
if ($value) {
$scope->setTag($key, $value);
}
}
if ($text instanceof Throwable) {
\Sentry\captureException($text);
} else {
$event = Event::createEvent();
$event->setMessage($data['message']);
$event->setLevel($this->getLogLevel($level));
\Sentry\captureEvent($event, EventHint::fromArray(array_filter([
'exception' => $data['exception'] ?? null,
])));
}
});
}
}
/**
* Calls the extra callback if it exists
*
* @param mixed $text
* @param array $data
*
* @return array
*/
public function runExtraCallback($text, $data)
{
if (is_callable($this->extraCallback)) {
$data['extra'] = call_user_func($this->extraCallback, $text, $data['extra'] ?? []);
}
return $data;
}
/**
* Returns the text display of the specified level for the Sentry.
*
* @deprecated Deprecated from 1.5, will remove in 2.0
*
* @param int $level The message level, e.g. [[LEVEL_ERROR]], [[LEVEL_WARNING]].
*
* @return string
*/
public static function getLevelName($level)
{
static $levels = [
Logger::LEVEL_ERROR => 'error',
Logger::LEVEL_WARNING => 'warning',
Logger::LEVEL_INFO => 'info',
Logger::LEVEL_TRACE => 'debug',
Logger::LEVEL_PROFILE_BEGIN => 'debug',
Logger::LEVEL_PROFILE_END => 'debug',
];
return $levels[$level] ?? 'error';
}
/**
* Translates Yii2 log levels to Sentry Severity.
*
* @param int $level
*
* @return Severity
*/
protected function getLogLevel($level): Severity
{
switch ($level) {
case Logger::LEVEL_PROFILE:
case Logger::LEVEL_PROFILE_BEGIN:
case Logger::LEVEL_PROFILE_END:
case Logger::LEVEL_TRACE:
return Severity::debug();
case Logger::LEVEL_WARNING:
return Severity::warning();
case Logger::LEVEL_ERROR:
return Severity::error();
case Logger::LEVEL_INFO:
default:
return Severity::info();
}
}
}