Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Collecting breadcrumbs and stacktraces #54

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,22 @@ Example:

More about tags see https://docs.sentry.io/learn/context/#tagging-events


### Breadcrumbs

All messages will be added to Breadcrumbs display.

You can mark breadcrumbs with type:

```php
\Yii::warning([
'msg' => 'message',
'type' => \Sentry\Breadcrumb::TYPE_HTTP,
], 'category');
```

More about breadcrumbs see https://docs.sentry.io/product/error-monitoring/breadcrumbs/

### Additional context

You can add additional context (such as user information, fingerprint, etc) by calling `\Sentry\configureScope()` before logging.
Expand Down
137 changes: 108 additions & 29 deletions src/SentryTarget.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@

namespace notamedia\sentry;

use Sentry\Breadcrumb;
use Sentry\ClientBuilder;
use Sentry\Event;
use Sentry\EventHint;
use Sentry\Frame;
use Sentry\Integration\ErrorListenerIntegration;
use Sentry\Integration\ExceptionListenerIntegration;
use Sentry\Integration\FatalErrorListenerIntegration;
use Sentry\Integration\IntegrationInterface;
use Sentry\SentrySdk;
use Sentry\Serializer\RepresentationSerializer;
use Sentry\Severity;
use Sentry\StacktraceBuilder;
use Sentry\State\Scope;
use Throwable;
use Yii;
Expand Down Expand Up @@ -48,6 +52,13 @@ class SentryTarget extends Target
*/
public $extraCallback;

/**
* @var StacktraceBuilder Builder fo creation stack trace frames
*
* It available in \Sentry\Client, but it`s private.
*/
protected $stacktraceBuilder;

/**
* @inheritDoc
*/
Expand Down Expand Up @@ -77,6 +88,8 @@ public function __construct($config = [])
});

SentrySdk::init()->bindClient($builder->getClient());

$this->stacktraceBuilder = new StacktraceBuilder($options, new RepresentationSerializer($options));
}

/**
Expand All @@ -87,13 +100,41 @@ protected function getContextMessage()
return '';
}

/**
* @inheritdoc
*/
public function collect($messages, $final)
{
foreach ($messages as $message) {
list($text, $level, $category, $timestamp, $traces) = $message;

[$message, $tags, $exception, $type, $extra] = $this->parseText($text);

$metadata = [];
if (!empty($tags))
$metadata['tags'] = $tags;

if (!empty($exception))
$metadata['exception'] = $exception;

if (!empty($extra))
$metadata['extra'] = $extra;

// $timestamp parameter will be added soon
// @see https://github.com/getsentry/sentry-php/pull/1193
$bc = new Breadcrumb($this->getLogLevel($level), $type, $category, $message, $metadata, $timestamp);
\Sentry\addBreadcrumb($bc);
}
parent::collect($messages, $final);
}

/**
* @inheritdoc
*/
public function export()
{
foreach ($this->messages as $message) {
[$text, $level, $category] = $message;
[$text, $level, $category, $timestamp, $traces] = $message;

$data = [
'message' => '',
Expand All @@ -113,33 +154,13 @@ public function export()
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']);
}
} catch (Throwable $e) {
}

if (isset($text['exception']) && $text['exception'] instanceof Throwable) {
$data['exception'] = $text['exception'];
unset($text['exception']);
}
\Sentry\withScope(function (Scope $scope) use ($text, $level, $timestamp, $traces, $data) {
[$data['message'], $tags, $data['exception'], $breadcrumbType, $data['extra']] = $this->parseText($text);

$data['extra'] = $text;
} else {
$data['message'] = (string) $text;
}
$data['tags'] = ArrayHelper::merge($data['tags'], $tags);

if ($this->context) {
$data['extra']['context'] = parent::getContextMessage();
Expand All @@ -148,9 +169,7 @@ public function export()
$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);
Expand All @@ -163,15 +182,75 @@ public function export()
$event = Event::createEvent();
$event->setMessage($data['message']);
$event->setLevel($this->getLogLevel($level));
$event->setTimestamp($timestamp);

\Sentry\captureEvent($event, EventHint::fromArray(array_filter([
'exception' => $data['exception'] ?? null,
'extra' => $data['extra'] ?? [],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check this line, it seems not the same extra data that we can attach to scope

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All scope extra data will be directly copied into extra field of the each event in this method, so both extra arrays has same format

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But it from Event object, not from EventHint
I've tested and received additional data in Sentry only with old code with setting extra on Event object
As I see, data from EventHint used in this and from extra only in this

'stacktrace' => $this->buildStacktrace($traces),
])));
}
});
}
}

/**
* Parse the text variable
* @param $text
* @return array
*/
protected function parseText($text)
{
$message = '';
$tags = [];
$exception = null;
$extra = [];
$type = Breadcrumb::TYPE_DEFAULT;
if (is_array($text)) {
if (isset($text['msg'])) {
$message = (string)$text['msg'];
unset($text['msg']);
}

if (isset($text['message'])) {
$message = (string)$text['message'];
unset($text['message']);
}

if (isset($text['tags'])) {
$tags = (array)$text['tags'];
unset($text['tags']);
}

if (isset($text['type'])) {
$type = $text['type'];
unset($text['type']);
}

if (isset($text['exception']) && $text['exception'] instanceof Throwable) {
$exception = $text['exception'];
unset($text['exception']);
}
$extra = $text;
} else {
$message = (string)$text;
}
return [$message, $tags, $exception, $type, $extra];
}

/**
* Builds \Sentry\Stacktrace from traces array
* @param $traces Yii message traces
* @return null|\Sentry\Stacktrace
*/
protected function buildStacktrace($traces)
{
if (is_array($traces) && !empty($traces)) {
return $this->stacktraceBuilder->buildFromBacktrace($traces, Frame::INTERNAL_FRAME_FILENAME, 0);
}
return null;
}

/**
* Calls the extra callback if it exists
*
Expand Down
Loading