vendor/eightpoints/guzzle-bundle/src/Middleware/LogMiddleware.php line 49

Open in your IDE?
  1. <?php
  2. namespace EightPoints\Bundle\GuzzleBundle\Middleware;
  3. use GuzzleHttp\Exception\RequestException;
  4. use GuzzleHttp\MessageFormatter;
  5. use EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface;
  6. class LogMiddleware
  7. {
  8.     /** @var \GuzzleHttp\MessageFormatter */
  9.     protected $formatter;
  10.     /** @var \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface */
  11.     protected $logger;
  12.     /**
  13.      * @param \EightPoints\Bundle\GuzzleBundle\Log\LoggerInterface $logger
  14.      * @param \GuzzleHttp\MessageFormatter $formatter
  15.      */
  16.     public function __construct(LoggerInterface $loggerMessageFormatter $formatter)
  17.     {
  18.         $this->logger    $logger;
  19.         $this->formatter $formatter;
  20.     }
  21.     /**
  22.      * Logging each Request
  23.      *
  24.      * @return \Closure
  25.      */
  26.     public function log() : \Closure
  27.     {
  28.         $logger    $this->logger;
  29.         $formatter $this->formatter;
  30.         return function (callable $handler) use ($logger$formatter) {
  31.             return function ($request, array $options) use ($handler$logger$formatter) {
  32.                 // generate id that will be used to supplement the log with information
  33.                 $requestId uniqid('eight_points_guzzle_');
  34.                 // initial registration of log
  35.                 $logger->info(''compact('request''requestId'));
  36.                 // this id will be used by RequestTimeMiddleware
  37.                 $options['request_id'] = $requestId;
  38.                 return $handler($request$options)->then(
  39.                     function ($response) use ($logger$request$formatter$requestId) {
  40.                         $message $formatter->format($request$response);
  41.                         $context compact('request''response''requestId');
  42.                         $logger->info($message$context);
  43.                         return $response;
  44.                     },
  45.                     function ($reason) use ($logger$request$formatter$requestId) {
  46.                         $response $reason instanceof RequestException $reason->getResponse() : null;
  47.                         $message  $formatter->format($request$response$reason);
  48.                         $context  compact('request''response''requestId');
  49.                         $logger->notice($message$context);
  50.                         return \GuzzleHttp\Promise\Create::rejectionFor($reason);
  51.                     }
  52.                 );
  53.             };
  54.         };
  55.     }
  56. }