vendor/overblog/graphql-bundle/src/EventListener/ErrorLoggerListener.php line 28

  1. <?php
  2. declare(strict_types=1);
  3. namespace Overblog\GraphQLBundle\EventListener;
  4. use GraphQL\Error\UserError;
  5. use Overblog\GraphQLBundle\Error\UserWarning;
  6. use Overblog\GraphQLBundle\Event\ErrorFormattingEvent;
  7. use Psr\Log\LoggerInterface;
  8. use Psr\Log\LogLevel;
  9. use Psr\Log\NullLogger;
  10. use Throwable;
  11. use function get_class;
  12. use function sprintf;
  13. final class ErrorLoggerListener
  14. {
  15.     public const DEFAULT_LOGGER_SERVICE 'logger';
  16.     private LoggerInterface $logger;
  17.     public function __construct(LoggerInterface $logger null)
  18.     {
  19.         $this->logger $logger ?? new NullLogger();
  20.     }
  21.     public function onErrorFormatting(ErrorFormattingEvent $event): void
  22.     {
  23.         $error $event->getError();
  24.         $exception $error->getPrevious();
  25.         if (null === $exception) {
  26.             return;
  27.         }
  28.         if ($exception instanceof UserError) {
  29.             if ($exception->getPrevious()) {
  30.                 $this->log($exception->getPrevious());
  31.             }
  32.             return;
  33.         }
  34.         if ($exception instanceof UserWarning) {
  35.             if ($exception->getPrevious()) {
  36.                 $this->log($exception->getPrevious(), LogLevel::WARNING);
  37.             }
  38.             return;
  39.         }
  40.         $this->log($exceptionLogLevel::CRITICAL);
  41.     }
  42.     public function log(Throwable $exceptionstring $errorLevel LogLevel::ERROR): void
  43.     {
  44.         $message sprintf(
  45.             '[GraphQL] %s: %s[%d] (caught throwable) at %s line %s.',
  46.             get_class($exception),
  47.             $exception->getMessage(),
  48.             $exception->getCode(),
  49.             $exception->getFile(),
  50.             $exception->getLine()
  51.         );
  52.         $this->logger->log($errorLevel$message, ['exception' => $exception]);
  53.     }
  54. }