src/EventListener/ExceptionSubscriber.php line 28

  1. <?php
  2. namespace App\EventListener;
  3. use App\Entity\Admin\ApiLog;
  4. use App\Entity\SystemLog;
  5. use App\Service\Logger\LoggerService;
  6. use Doctrine\ORM\EntityManager;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpFoundation\RequestStack;
  12. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  13. use Symfony\Component\HttpKernel\KernelEvents;
  14. class ExceptionSubscriber implements EventSubscriberInterface
  15. {
  16.     public function __construct(readonly EntityManagerInterface $entityManager, readonly ManagerRegistry $managerRegistry,readonly RequestStack $requestStack)
  17.     {
  18.     }
  19.     public function onKernelException(ExceptionEvent $event): void
  20.     {
  21.         $this->logError($event->getThrowable()->getMessage());
  22.     }
  23.     public function onCommandException(ConsoleErrorEvent $event): void
  24.     {
  25.         $this->logError($event->getError());
  26.     }
  27.     public function logError(string $message): void
  28.     {
  29.         //reopen the entity manager if it is closed
  30.         if(!$this->entityManager->isOpen()){
  31.             $this->managerRegistry->resetManager();
  32.         }
  33.         $ip "undefined";
  34.         $request $this->requestStack->getCurrentRequest();
  35.         if ($request) {
  36.             $ip $request->getClientIp();
  37.         }
  38.         $systemLog = new ApiLog();
  39.         $germanTime = new \DateTimeImmutable();
  40.         $germanTime->setTimezone(new \DateTimeZone('Europe/Berlin'));
  41.         $systemLog->setCreatedAt($germanTime);
  42.         $systemLog->setLog("[".$ip."]" " " $message);
  43.         $systemLog->setSuccess(false);
  44.         $this->entityManager->persist($systemLog);
  45.         $this->entityManager->flush();
  46.         //zähle alle system logs
  47.         $systemLogs $this->entityManager->getRepository(ApiLog::class)->findAll();
  48.         $countSystemLogs count($systemLogs);
  49.         // es soll nicht mehr als 10000 Einträge geben
  50.         if($countSystemLogs 10000){
  51.             //lösche den ältesten
  52.             $oldestSystemLog $this->entityManager->getRepository(ApiLog::class)->findOneBy([], ['createdAt' => 'ASC']);
  53.             $this->entityManager->remove($oldestSystemLog);
  54.         }
  55.     }
  56.     public static function getSubscribedEvents(): array
  57.     {
  58.         return [
  59.             KernelEvents::EXCEPTION => 'onKernelException',
  60.             ConsoleErrorEvent::class => 'onCommandException'
  61.         ];
  62.     }
  63. }