src/EventListener/ExceptionSubscriber.php line 23
<?php
namespace App\EventListener;
use App\Entity\Admin\ApiLog;
use App\Entity\SystemLog;
use App\Service\Logger\LoggerService;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(readonly EntityManagerInterface $entityManager, readonly ManagerRegistry $managerRegistry,readonly RequestStack $requestStack)
{
}
public function onKernelException(ExceptionEvent $event): void
{
$this->logError($event->getThrowable()->getMessage());
}
public function onCommandException(ConsoleErrorEvent $event): void
{
$this->logError($event->getError());
}
public function logError(string $message): void
{
//reopen the entity manager if it is closed
if(!$this->entityManager->isOpen()){
$this->managerRegistry->resetManager();
}
$ip = "undefined";
$request = $this->requestStack->getCurrentRequest();
if ($request) {
$ip = $request->getClientIp();
}
$systemLog = new ApiLog();
$germanTime = new \DateTimeImmutable();
$germanTime->setTimezone(new \DateTimeZone('Europe/Berlin'));
$systemLog->setCreatedAt($germanTime);
$systemLog->setLog("[".$ip."]" . " " . $message);
$systemLog->setSuccess(false);
$this->entityManager->persist($systemLog);
$this->entityManager->flush();
//zähle alle system logs
$systemLogs = $this->entityManager->getRepository(ApiLog::class)->findAll();
$countSystemLogs = count($systemLogs);
// es soll nicht mehr als 10000 Einträge geben
if($countSystemLogs > 10000){
//lösche den ältesten
$oldestSystemLog = $this->entityManager->getRepository(ApiLog::class)->findOneBy([], ['createdAt' => 'ASC']);
$this->entityManager->remove($oldestSystemLog);
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
ConsoleErrorEvent::class => 'onCommandException'
];
}
}