Skip to content

Instantly share code, notes, and snippets.

@appkr
Last active May 7, 2024 10:08
Show Gist options
  • Save appkr/d04ebca37ae665612fcdbe44ea016bd9 to your computer and use it in GitHub Desktop.
Save appkr/d04ebca37ae665612fcdbe44ea016bd9 to your computer and use it in GitHub Desktop.
Guzzle RequestResponseLog Middleware Example
<?php
namespace App\Providers;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
class LoggableGuzzleClientProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(Client::class, function (Application $app) {
$logger = $app->make(LoggerInterface::class);
$stack = HandlerStack::create();
$stack->push(Middleware::tap(null, function (RequestInterface $req, array $options = [], PromiseInterface $promise) use ($logger) {
$promise->then(
function (ResponseInterface $res) use ($req, $logger) {
$logger->info('GuzzleHttp Request-Response Log', [
'request' => [
'uri' => "{$req->getMethod()} {$req->getUri()}",
'headers' => $req->getHeaders(),
'body' => $req->getBody()->getContents(),
],
'response' => [
'status' => $res->getStatusCode(),
'headers' => $res->getHeaders(),
'body' => $res->getBody()->getContents(),
]
]);
// Move pointer to the beginning of the stream
$res->getBody()->rewind();
},
function (RequestException $e) use ($req, $logger) {
$logger->error('GuzzleHttp Request-Response Log', [
'request' => [
'uri' => "{$req->getMethod()} {$req->getUri()}",
'headers' => $req->getHeaders(),
'body' => $req->getBody()->getContents(),
],
'error' => [
'status' => $e->hasResponse() ? $e->getResponse()->getStatusCode() : $e->getCode(),
'message' => $e->getMessage(),
'body' => $e->hasResponse() ? $e->getResponse()->getBody()->getContents() : null,
]
]);
}
);
}));
$client = new Client([
'handler' => $stack,
'base_uri' => "https://api.github.com",
]);
return $client;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment