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

[FEATURE] Special handling for log records with "exception" keys #107

Closed
wants to merge 1 commit into from
Closed
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
39 changes: 38 additions & 1 deletion Classes/SentryLogWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Networkteam\SentryClient\Service\ConfigurationService;
use Networkteam\SentryClient\Service\SentryService;
use Networkteam\SentryClient\Trait\IgnoreMessage;
use Sentry\Breadcrumb;
use Sentry\Event;
use Sentry\Stacktrace;
use Sentry\State\Scope;
Expand Down Expand Up @@ -36,6 +37,12 @@ public function writeLog(LogRecord $record)
if (SentryService::isEnabled()
&& $this->shouldHandleLogMessage($record)
) {
$data = $record->getData();
if (isset($data['exception']) && $data['exception'] instanceof \Throwable) {
$this->writeException($record);
return $this;
}

withScope(function (Scope $scope) use ($record): void {
$scope->setExtra('component', $record->getComponent());
if ($record->getData()) {
Expand All @@ -46,7 +53,7 @@ public function writeLog(LogRecord $record)
$record->getMessage(),
$record->getComponent()
]);

$message = $record->getMessage();
if (method_exists($this, 'interpolate')) {
$message = $this->interpolate($message, $record->getData());
Expand All @@ -59,6 +66,36 @@ public function writeLog(LogRecord $record)
return $this;
}

/**
* Report a log record with an 'exception' object in its data.
*
* Exception objects in Sentry data properties do not get serialized
* and thus get lost.
* To keep them and their stacktrace, we send it as exception to Sentry.
* The log message is kept as breadcrumb.
*
* TYPO3 scheduler logs such messages when tasks fail.
*/
protected function writeException(LogRecord $record): void
{
$data = $record->getData();
$exception = $data['exception'];
unset($data['exception']);

withScope(function (Scope $scope) use ($data, $exception, $record): void {
$scope->setExtra('component', $record->getComponent());
$scope->setExtra('data', $data);

$message = $record->getMessage();
if (method_exists($this, 'interpolate')) {
$message = $this->interpolate($message, $record->getData());
}
$scope->addBreadcrumb(new Breadcrumb('error', 'default', 'log message', $message, []));

Client::captureException($exception);
});
}

protected function shouldHandleLogMessage(LogRecord $logRecord): bool
{
if ($this->shouldIgnoreMessage($logRecord->getMessage())) {
Expand Down
Loading