How do I log requests and responses in Guzzle?

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. When working on a project, you might need to log requests and responses for debugging purposes, to audit traffic, or for compliance reasons.

Guzzle provides middleware that you can use to hook into the request and response lifecycle. Here’s how you can log requests and responses using Guzzle's middleware and the Monolog library for logging.

First, make sure you have Guzzle and Monolog installed via Composer:

composer require guzzlehttp/guzzle
composer require monolog/monolog

Then you can set up a stack with middleware to log your requests and responses.

Here’s an example of how to do this in PHP:

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Create a log channel
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::DEBUG));

$stack = HandlerStack::create();

$stack->push(Middleware::log(
    $log,
    new \GuzzleHttp\MessageFormatter('{req_headers} - {req_body} - {res_headers} - {res_body}')
));

$client = new Client(['handler' => $stack]);

// Perform a request
$response = $client->request('GET', 'https://httpbin.org/get');

// Print the response body
echo $response->getBody();

In this example:

  1. We create a Logger instance with Monolog which logs to a specified file at the DEBUG level.
  2. We create a Guzzle HandlerStack and push a logging middleware onto it.
  3. The logging middleware uses a MessageFormatter which defines the format of the log messages. {req_headers}, {req_body}, {res_headers}, and {res_body} are template variables that will be replaced with the actual request headers, request body, response headers, and response body, respectively.
  4. We create a Guzzle Client instance with the custom handler stack.
  5. Finally, we make a GET request to https://httpbin.org/get and print the response.

The MessageFormatter allows you to customize the log message format to include various parts of the request and response. Check the Guzzle documentation for the full list of available template variables.

Remember to replace 'path/to/your.log' with the actual path to your log file. Ensure that the file is writable by the script.

Monolog supports various handlers that you could use to log to different storage types, such as Syslog, database, or remote services. Choose the appropriate handler based on your project requirements.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon