src/Event/ExceptionListener.php line 28
<?php
declare(strict_types=1);
namespace App\Event;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Throwable;
class ExceptionListener implements EventSubscriberInterface
{
public function __construct(
private readonly LoggerInterface $errorLogger,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => ['onKernelException'],
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$request = $event->getRequest();
$this->log($request, $exception);
}
private function log(Request $request, Throwable $e): void
{
$this->errorLogger->error(
'error',
[
'requestId' => $request->attributes->get('requestId'),
'request' => [
'method' => $request->getMethod(),
'uri' => $request->getUri(),
'host' => $request->headers->get('Host'),
'ipAddress' => $request->getClientIp(),
'remoteAddr' => $request->server->get('REMOTE_ADDR'),
'headers' => $request->headers->all(),
'query' => $request->query->all(),
'requestParams' => $request->request->all(),
],
'exception' => [
'code' => $e->getCode(),
'message' => $e->getMessage(),
'exception' => $e,
'trace' => $e->getTraceAsString(),
],
],
);
}
}