DEV Community

Cover image for Log Request Body in Guzzle
Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on

Log Request Body in Guzzle

Debugging when using Guzzle, is quiet easy by providing the debug key in the payload:

$client->request('GET', '/url, ['debug' => true]);
Enter fullscreen mode Exit fullscreen mode

This is quiet easy and not an issue if your are not passing any body content, using only query string to dump what's been request.

It will different story if you are sending JSON content - you need to know the write data send to your URI destination.

You can create a middleware for this purpose.

TLDR


use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Psr\Http\Message\RequestInterface;

$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());

$middleware = Middleware::tap(function (RequestInterface $request) {
    if(config('services.api.debug')) {
        $body = (string) $request->getBody();

        if(!empty($body)) {
            $body = json_decode($body, JSON_OBJECT_AS_ARRAY);
        }

        logger()->channel('api')->info([
            'url' => $request->getUri(),
            'body' => $body,
            'headers' => $request->getHeaders(),
        ]);
    }
});

$stack->push($middleware);

$client = new Client(
    [
        'base_uri' => config('services.api.base_url'),
        'handler' => $stack,
    ]
);

$client->request('GET', '/url', ['json' => ['abc' => 123]]);
Enter fullscreen mode Exit fullscreen mode

With this piece of codes, it helps you to debug what kind of data being send before request is send.

p/s: I'm using Laravel, hence some of the syntax related to Laravel.

Discussion (0)