src/EventListener/LogPublisherSubscriber.php line 26

  1. <?php
  2. namespace App\EventListener;
  3. use App\Event\HttpLogEvent;
  4. use App\Service\LogPublisher\Domain\HttpLog;
  5. use App\Service\LogPublisher\LogPublisherServiceInterface;
  6. use Psr\Log\LoggerInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class LogPublisherSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(
  11.         private LoggerInterface $logger,
  12.         private LogPublisherServiceInterface $logPublisherService,
  13.         private bool $httpLoggingEnabled,
  14.     ) {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             HttpLogEvent::class => 'logHttpEvent',
  20.         ];
  21.     }
  22.     public function logHttpEvent(HttpLogEvent $event): void
  23.     {
  24.         try {
  25.             // must be non-fatal
  26.             $httpLog $this->buildHttpLog($event);
  27.             // $this->logger->notice(json_encode($httpLog));
  28.             // Local debug: Use one of the following two options
  29.             // $log = json_encode($httpLog);
  30.             // $log = $httpLog->__toString();
  31.             // file_put_contents('/opt/gateway-2/gateway-2/output'.time().'.txt', $log."\n\n", FILE_APPEND | LOCK_EX);
  32.             // TODO: Sanitise sensitive data in http request/response
  33.             // TODO: Restrict to trigger only in booking/cancellation flow
  34.             if ($this->httpLoggingEnabled) {
  35.                 $this->logPublisherService->logHttp($httpLog);
  36.             }
  37.         } catch (\Throwable $e) {
  38.             $this->logger->error('Error when trying to publish logs: '.$e->getMessage());
  39.         }
  40.     }
  41.     private function buildHttpLog(HttpLogEvent $event): HttpLog
  42.     {
  43.         $request $event->getRequest();
  44.         $response $event->getResponse();
  45.         $uri $request->getUri();
  46.         $statusCode $response->getStatusCode();
  47.         $dateTime date('c'time());
  48.         return new HttpLog(
  49.             url$uri,
  50.             request$request,
  51.             response$response,
  52.             status$statusCode,
  53.             dateTime$dateTime,
  54.         );
  55.     }
  56. }