diff --git a/Config/config.php b/Config/config.php new file mode 100644 index 0000000..6605244 --- /dev/null +++ b/Config/config.php @@ -0,0 +1,38 @@ + 'Custom Sentry Error handler', + 'description' => 'Logs errors to Sentry.', + 'version' => '1.0', + 'author' => 'SWIS', + + 'services' => [ + 'other' => [ + 'custom_sentry.event_listener' => [ + 'class' => MauticPlugin\SwisSentryBundle\EventListener\SentryExceptionListener::class, + 'arguments' => [], + 'tags' => [ + 'kernel.event_listener', + 'kernel.event_listener', + ], + 'tagArguments' => [ + [ + 'event' => 'kernel.exception', + 'method' => 'handleExceptionEvent', + /* + * 255 is the Mautic error-page priority, we want to log error's before it stops propagation. + * @see app/bundles/CoreBundle/Config/config.php + */ + 'priority' => 256, + ], + [ + 'event' => 'kernel.terminate', + 'method' => 'handleKernelTerminateEvent', + ], + ], + ], + ], + ], +]; diff --git a/CustomSentryBundle.php b/CustomSentryBundle.php new file mode 100644 index 0000000..e980777 --- /dev/null +++ b/CustomSentryBundle.php @@ -0,0 +1,11 @@ + getenv('SENTRY_DSN'), + 'environment' => getenv('APP_ENV') ?: 'unknown', + ]); + } + + public function handleExceptionEvent(ExceptionEvent $event): void + { + \Sentry\captureException($event->getThrowable()); + $event->getRequest()->attributes->set(SentryExceptionListener::class, true); + } + + public function handleKernelTerminateEvent(TerminateEvent $event): void + { + $request = $event->getRequest(); + $response = $event->getResponse(); + + // If already logged the exception, we don't log the Termination event. + if ($request->attributes->get(SentryExceptionListener::class, false)) { + return; + } + + if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) { + \Sentry\captureException(new \RuntimeException(sprintf('Terminated route @ "%s"', $request->getRequestUri()))); + } + } +} diff --git a/composer.json b/composer.json index 6736780..4ffd54f 100644 --- a/composer.json +++ b/composer.json @@ -20,8 +20,11 @@ "role": "Developer" } ], + "minimum-stability": "dev", "require": { - "php": "^7.4|^8.0" + "php": "^7.4|^8.0", + "sentry/sentry": "*", + "sentry/sentry-symfony": "*" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.8", @@ -32,6 +35,7 @@ "fix-style": "php-cs-fixer fix" }, "extra": { + "install-directory-name": "MauticSentryBundle", "branch-alias": { "dev-master": "1.0-dev" }