vendor/mdm-ecom/logger-bundle/EventSubscriber/LoggingSubscriber.php line 197

Open in your IDE?
  1. <?php
  2. namespace MDM\LoggerBundle\EventSubscriber;
  3. use MDM\LoggerBundle\Events\RetrieveTransactionIdEvent;
  4. use MDM\LoggerBundle\Logger\LoggerService;
  5. use MDM\LoggerBundle\Messenger\Stamps\TransactionIdStamp;
  6. use Symfony\Component\Console\Command\Command;
  7. use Symfony\Component\Console\ConsoleEvents;
  8. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  9. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  10. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  13. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  14. use Symfony\Component\HttpKernel\Event\RequestEvent;
  15. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  16. use Symfony\Component\HttpKernel\Event\TerminateEvent;
  17. use Symfony\Component\HttpKernel\KernelEvents;
  18. use Symfony\Component\Messenger\Event\AbstractWorkerMessageEvent;
  19. use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
  20. use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;
  21. use Symfony\Component\Messenger\Event\WorkerMessageReceivedEvent;
  22. use Symfony\Component\Stopwatch\Stopwatch;
  23. /**
  24.  * Class LoggingSubscriber
  25.  * @package App\EventSubscriber
  26.  */
  27. class LoggingSubscriber implements EventSubscriberInterface
  28. {
  29.     private const STOPWATCH_REQUEST 'request';
  30.     private const STOPWATCH_WORKER 'worker';
  31.     private const STOPWATCH_COMMAND 'command';
  32.     /**
  33.      * @var LoggerService
  34.      */
  35.     private $loggerService;
  36.     /**
  37.      * @var string|null
  38.      */
  39.     private $routeName;
  40.     /**
  41.      * @var Stopwatch
  42.      */
  43.     private $stopwatch;
  44.     private $transactionId;
  45.     /**
  46.      * LoggingSubscriber constructor.
  47.      * @param LoggerService $loggerService
  48.      */
  49.     public function __construct(LoggerService $loggerService)
  50.     {
  51.         $this->stopwatch = new Stopwatch();
  52.         $this->loggerService $loggerService;
  53.     }
  54.     /**
  55.      * @inheritDoc
  56.      */
  57.     public static function getSubscribedEvents()
  58.     {
  59.         return [
  60.             KernelEvents::REQUEST => ['onKernelRequest'50],
  61.             KernelEvents::CONTROLLER => ['onKernelController'50],
  62.             KernelEvents::TERMINATE => ['onKernelTerminate', -10],
  63.             KernelEvents::EXCEPTION => ['onKernelException'20],
  64.             WorkerMessageReceivedEvent::class => ['onWorkerMessageReceived'30],
  65.             WorkerMessageFailedEvent::class => ['onWorkerMessageFailed'20],
  66.             WorkerMessageHandledEvent::class => ['onWorkerMessageHandled'20],
  67.             RetrieveTransactionIdEvent::class => 'onRetrieveTransactionId',
  68.             ConsoleEvents::COMMAND => ['onConsoleCommand'],
  69.             ConsoleEvents::ERROR => ['onConsoleError'],
  70.             ConsoleEvents::TERMINATE => ['onConsoleTerminate', -10]
  71.         ];
  72.     }
  73.     /**
  74.      * @param ConsoleCommandEvent $event
  75.      */
  76.     public function onConsoleCommand(ConsoleCommandEvent $event)
  77.     {
  78.         $this->stopwatch->reset();
  79.         $this->stopwatch->start(self::STOPWATCH_COMMAND);
  80.         $this->transactionId uniqid(''true);
  81.         $this->loggerService->debug("New TransactionId created: {$this->transactionId}");
  82.         $this->loggerService->addContext([
  83.             'transaction_id' => $this->transactionId,
  84.             'trigger' => 'Command: ' $event->getCommand()->getName()
  85.         ]);
  86.     }
  87.     /**
  88.      * @param ConsoleErrorEvent $event
  89.      */
  90.     public function onConsoleError(ConsoleErrorEvent $event)
  91.     {
  92.         $this->loggerService->logException($event->getError());
  93.     }
  94.     /**
  95.      * @param ConsoleTerminateEvent $event
  96.      */
  97.     public function onConsoleTerminate(ConsoleTerminateEvent $event)
  98.     {
  99.         if ($this->stopwatch->isStarted(self::STOPWATCH_COMMAND)) {
  100.             $this->stopwatch->stop(self::STOPWATCH_COMMAND);
  101.             $duration $this->stopwatch->getEvent(self::STOPWATCH_COMMAND)->getDuration();
  102.             $this->loggerService->addContext(['duration' => $duration]);
  103.         }
  104.         $success $event->getExitCode() === Command::SUCCESS;
  105.         $this->loggerService->addContext(['status' => $success 'successful' 'failed']);
  106.         $this->loggerService->publishLog(
  107.             sprintf("%s command %s"$event->getCommand()->getName(), $success 'successful' 'failed')
  108.         );
  109.         $this->loggerService->clearContext();
  110.     }
  111.     /**
  112.      * @param RequestEvent $event
  113.      */
  114.     public function onKernelRequest(RequestEvent $event)
  115.     {
  116.         $this->stopwatch->start(self::STOPWATCH_REQUEST);
  117.         $request $event->getRequest();
  118.         // Attempt to retrieve existing request. If this event is triggered multiple times, we do not
  119.         // want to overwrite an already generated ID
  120.         if (!$this->transactionId) {
  121.             $this->transactionId $request->headers->get('transaction-id');
  122.         }
  123.         if (is_null($this->transactionId)) {
  124.             $this->transactionId uniqid(''true);
  125.             $this->loggerService->debug("New TransactionId created: {$this->transactionId}");
  126.         }
  127.         $request->attributes->set('transaction-id'$this->transactionId);
  128.         $this->loggerService->addContext([
  129.             'transaction_id' => $this->transactionId,
  130.             'basic_auth_user' => $request->headers->get('php-auth-user') ?? 'unknown',
  131.             'trigger' => 'Request: ' $event->getRequest()->getPathInfo()
  132.         ]);
  133.         $this->loggerService->logRequest($request);
  134.     }
  135.     /**
  136.      * @param ControllerEvent $event
  137.      */
  138.     public function onKernelController(ControllerEvent $event)
  139.     {
  140.         $request $event->getRequest();
  141.         $this->routeName $request->attributes->get('_route');
  142.     }
  143.     /**
  144.      * @param TerminateEvent $event
  145.      */
  146.     public function onKernelTerminate(TerminateEvent $event)
  147.     {
  148.         $response $event->getResponse();
  149.         $this->loggerService->logResponse($response$this->routeName);
  150.         if ($this->stopwatch->isStarted(self::STOPWATCH_REQUEST)) {
  151.             $this->stopwatch->stop(self::STOPWATCH_REQUEST);
  152.             $duration $this->stopwatch->getEvent(self::STOPWATCH_REQUEST)->getDuration();
  153.             $this->loggerService->addContext(['duration' => $duration]);
  154.             $this->stopwatch->reset();
  155.         }
  156.         $this->loggerService->addContext(
  157.             [
  158.                 'status' => ($response->getStatusCode() < 400) ? 'successful' 'failed',
  159.                 'status_code' => $response->getStatusCode()
  160.             ]
  161.         );
  162.         $this->loggerService->publishLog(
  163.             sprintf('%s %s'$this->routeName$response->isSuccessful() ? 'successful' 'failed')
  164.         );
  165.     }
  166.     /**
  167.      * @param RetrieveTransactionIdEvent $event
  168.      */
  169.     public function onRetrieveTransactionId(RetrieveTransactionIdEvent $event)
  170.     {
  171.         if (!$this->transactionId) {
  172.             $this->loggerService->warning('TransactionId not set yet!');
  173.         }
  174.         $event->setTransactionId($this->transactionId);
  175.     }
  176.     /**
  177.      * @param ExceptionEvent $event
  178.      */
  179.     public function onKernelException(ExceptionEvent $event)
  180.     {
  181.         $this->loggerService->logException($event->getThrowable());
  182.     }
  183.     /**
  184.      * @param WorkerMessageReceivedEvent $event
  185.      */
  186.     public function onWorkerMessageReceived(WorkerMessageReceivedEvent $event)
  187.     {
  188.         /** @var TransactionIdStamp $id */
  189.         $id $event->getEnvelope()->last(TransactionIdStamp::class);
  190.         $this->stopwatch->reset();
  191.         $this->stopwatch->start(self::STOPWATCH_WORKER);
  192.         $this->transactionId $id $id->getTransactionId() : null;
  193.         if (is_null($this->transactionId)) {
  194.             $this->transactionId uniqid(''true);
  195.             $this->loggerService->debug("New TransactionId created: {$this->transactionId}");
  196.         }
  197.         $this->loggerService->addContext([
  198.             'transaction_id' => $this->transactionId,
  199.             'trigger' => 'Message: ' $event->getReceiverName()
  200.         ]);
  201.     }
  202.     /**
  203.      * @param WorkerMessageHandledEvent $event
  204.      */
  205.     public function onWorkerMessageHandled(WorkerMessageHandledEvent $event)
  206.     {
  207.         $this->onWorkerComplete($eventtrue);
  208.     }
  209.     /**
  210.      * @param WorkerMessageFailedEvent $event
  211.      */
  212.     public function onWorkerMessageFailed(WorkerMessageFailedEvent $event)
  213.     {
  214.         $this->onWorkerComplete($eventfalse);
  215.     }
  216.     /**
  217.      * @param AbstractWorkerMessageEvent $event
  218.      * @param bool $success
  219.      */
  220.     protected function onWorkerComplete(AbstractWorkerMessageEvent $eventbool $success)
  221.     {
  222.         if ($this->stopwatch->isStarted(self::STOPWATCH_WORKER)) {
  223.             $this->stopwatch->stop(self::STOPWATCH_WORKER);
  224.             $duration $this->stopwatch->getEvent(self::STOPWATCH_WORKER)->getDuration();
  225.             $this->loggerService->addContext(['duration' => $duration]);
  226.         }
  227.         $this->loggerService->addContext(['status' => $success 'successful' 'failed']);
  228.         $this->loggerService->publishLog(
  229.             sprintf("%s Worker %s"$event->getReceiverName(), $success 'successful' 'failed')
  230.         );
  231.         $this->loggerService->clearContext();
  232.     }
  233. }