src/Event/ExceptionListener.php line 28

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Event;
  4. use Psr\Log\LoggerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Throwable;
  10. class ExceptionListener implements EventSubscriberInterface
  11. {
  12.     public function __construct(
  13.         private readonly LoggerInterface $errorLogger,
  14.     ) {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::EXCEPTION => ['onKernelException'],
  20.         ];
  21.     }
  22.     public function onKernelException(ExceptionEvent $event): void
  23.     {
  24.         $exception $event->getThrowable();
  25.         $request $event->getRequest();
  26.         $this->log($request$exception);
  27.     }
  28.     private function log(Request $requestThrowable $e): void
  29.     {
  30.         $this->errorLogger->error(
  31.             'error',
  32.             [
  33.                 'requestId' => $request->attributes->get('requestId'),
  34.                 'request' => [
  35.                     'method' => $request->getMethod(),
  36.                     'uri' => $request->getUri(),
  37.                     'host' => $request->headers->get('Host'),
  38.                     'ipAddress' => $request->getClientIp(),
  39.                     'remoteAddr' => $request->server->get('REMOTE_ADDR'),
  40.                     'headers' => $request->headers->all(),
  41.                     'query' => $request->query->all(),
  42.                     'requestParams' => $request->request->all(),
  43.                 ],
  44.                 'exception' => [
  45.                     'code' => $e->getCode(),
  46.                     'message' => $e->getMessage(),
  47.                     'exception' => $e,
  48.                     'trace' => $e->getTraceAsString(),
  49.                 ],
  50.             ],
  51.         );
  52.     }
  53. }