DIGITAL4FRONT / CODE BASE

PHP Guzzle: Log API Requests, URLs and Responses

Learn how to log outgoing API requests in PHP using Guzzle middleware. Capture request URLs, GET parameters, response status codes, execution times and errors without exposing API keys or requiring a logging framework.

Share

Guzzle can automatically log outgoing API requests using middleware. Instead of manually constructing every HTTP request just to capture its URL, you can intercept requests through Guzzle's HandlerStack and record their method, URL, response status and execution time. This works with custom PHP logging systems and does not require Monolog or another logging framework.

The important distinction is that GET parameters normally belong in the URL query string, not the request body. Guzzle's query option handles this automatically.

Why GET parameters disappear when using Guzzle Request

Consider an application that successfully calls an API using Guzzle's request() method:

php
<?php
$response = $client->request('GET', $endpoint, [
 'headers' => [
 'X-API-Key' => $apiKey,
 ],
 'query' => [
 'page' => 1,
 'limit' => 20,
 ],
]);

Guzzle creates a request containing the query parameters in its URL.

For example:

text
https://api.example.com/products?page=1&limit=20

A developer might try replacing this with a manually constructed PSR-7 request:

php
<?php
use GuzzleHttp\Psr7\Request;

$request = new Request(
 'GET',
 $endpoint,
 ['X-API-Key' => $apiKey],
 http_build_query($parameters)
);

$response = $client->send($request);

The problem is the fourth argument to the Request constructor.

That argument represents the HTTP request body. It does not append parameters to the URL.

Although HTTP requests can technically contain bodies with different methods, APIs expecting GET query parameters will not find those parameters in the request body.

The correct solution is to use Guzzle's query option or explicitly build the URI with its query string.

1. Construct a GET request correctly

If you need to create a PSR-7 Request object manually, append the encoded parameters to the URL.

php
<?php
require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Psr7\Request;

$parameters = [
 'page' => 1,
 'limit' => 20,
];

$query = http_build_query(
 $parameters,
 '',
 '&',
 PHP_QUERY_RFC3986
);

$request = new Request(
 'GET',
 'https://api.example.com/products?' . $query
);

echo (string) $request->getUri();


The output is:

text
https://api.example.com/products?page=1&limit=20

This example assumes the original endpoint does not already contain a query string. If it does, merge the parameters using URI-aware handling rather than blindly appending another question mark.

For ordinary API requests, Guzzle's query option is simpler and less error-prone.

See the Guzzle request options documentation for additional details.

2. Understanding getPath() versus getUri()

Another common problem involves extracting the URL from a request.

Consider:

php
<?php
$path = $request->getUri()->getPath();

For the example request, this returns:

text
/products

It does not include the scheme, hostname or query string.

To retrieve the complete URI, convert the URI object to a string:

php
<?php
$url = (string) $request->getUri();

This produces the full URL, including its query parameters.

However, be careful about writing that value directly into a log.

URLs can contain access tokens, email addresses, customer identifiers or other sensitive information. Logging the complete URI without filtering can expose information that should remain private.

A production logging system should record only the information required for troubleshooting.

3. Why Guzzle middleware is the better approach

Manually building requests just to inspect their URLs introduces unnecessary changes to working API integrations.

Guzzle middleware solves this problem by intercepting requests as they pass through the HTTP client.

A middleware component can inspect the request, execute the underlying HTTP handler and examine the resulting response or failure.

This means logging can be added once and applied to every request made through the configured client.

It also works with existing calls using request(), get(), post() and other Guzzle methods.

The standard HandlerStack preserves Guzzle's default request-processing behaviour while allowing additional middleware to be registered.

The official Guzzle middleware documentation explains the underlying handler architecture.

4. Complete PHP Guzzle API logging implementation

The following example creates a reusable Guzzle client with automatic logging.

It records the request method, a filtered URL, response status, execution time and error type when a request fails.

The example uses a custom logging callback that writes JSON records to a local file. You can replace that callback with your existing logging system without changing the middleware.

Requirements

Use PHP 8.0 or later with Composer and a compatible Guzzle 7 installation.

Install Guzzle:

bash
composer require guzzlehttp/guzzle

Create a private directory for logs outside the public web root:

bash
mkdir -p private

Make sure PHP can write to that directory.

Configure an environment variable named SERVICE_API_KEY containing the API key for your integration. Do not place production API keys directly in source code.

Complete example: api-client.php

php
<?php
declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Promise\RejectedPromise;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

function safeRequestUrl(RequestInterface $request): string
{
 $uri = $request->getUri()
 ->withUserInfo('')
 ->withFragment('');

 $params = [];
 parse_str($uri->getQuery(), $params);

 $approved = [];

 foreach (['page', 'limit'] as $name) {
 if (isset($params[$name]) && is_scalar($params[$name])) {
 $approved[$name] = substr(
 (string) $params[$name],
 0,
 32
 );
 }
 }

 return (string) $uri->withQuery(
 http_build_query(
 $approved,
 '',
 '&',
 PHP_QUERY_RFC3986
 )
 );
}

$logFile = __DIR__ . '/private/api-requests.jsonl';

$logEvent = static function (array $event) use ($logFile): void {
 try {
 $line = json_encode($event, JSON_THROW_ON_ERROR);

 if (file_put_contents(
 $logFile,
 $line . PHP_EOL,
 FILE_APPEND | LOCK_EX
 ) === false) {
 error_log('API logging failed.');
 }
 } catch (Throwable $e) {
 error_log('API logging failed.');
 }
};

$stack = HandlerStack::create();

$stack->push(
 static function (callable $handler) use ($logEvent): callable {
 return static function (
 RequestInterface $request,
 array $options
 ) use ($handler, $logEvent): PromiseInterface {
 $start = hrtime(true);

 $details = [
 'time' => gmdate(DATE_ATOM),
 'method' => $request->getMethod(),
 'url' => safeRequestUrl($request),
 ];

 $duration = static fn (): int => (int) round(
 (hrtime(true) - $start) / 1000000
 );

 try {
 $promise = $handler($request, $options);
 } catch (Throwable $e) {
 $logEvent($details + [
 'status' => null,
 'duration_ms' => $duration(),
 'error_type' => get_class($e),
 ]);

 throw $e;
 }

 return $promise->then(
 static function (
 ResponseInterface $response
 ) use ($logEvent, $details, $duration): ResponseInterface {
 $logEvent($details + [
 'status' => $response->getStatusCode(),
 'duration_ms' => $duration(),
 ]);

 return $response;
 },
 static function ($reason) use (
 $logEvent,
 $details,
 $duration
 ) {
 $logEvent($details + [
 'status' => null,
 'duration_ms' => $duration(),
 'error_type' => is_object($reason)
 ? get_class($reason)
 : 'rejected',
 ]);

 return new RejectedPromise($reason);
 }
 );
 };
 },
 'safe_api_logging'
);

$apiKey = getenv('SERVICE_API_KEY');

if (!is_string($apiKey) || $apiKey === '') {
 throw new RuntimeException(
 'SERVICE_API_KEY must be configured.'
 );
}

$client = new Client([
 'handler' => $stack,
 'base_uri' => 'https://api.example.com/',
 'timeout' => 10.0,
 'http_errors' => false,
 'allow_redirects' => false,
]);

try {
 $response = $client->get('products', [
 'headers' => [
 'X-API-Key' => $apiKey,
 ],
 'query' => [
 'page' => 1,
 'limit' => 20,
 ],
 ]);

 echo 'HTTP ' . $response->getStatusCode() . PHP_EOL;

 $data = json_decode(
 (string) $response->getBody(),
 true,
 512,
 JSON_THROW_ON_ERROR
 );
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
 error_log('Request failed: ' . get_class($e));
} catch (JsonException $e) {
 error_log('API returned invalid JSON.');
}

Replace api.example.com and the example endpoint with your actual API service.

The code uses Guzzle's promise-based middleware interface and preserves the original response or rejection.

A successful response continues normally. A failed request remains failed rather than being silently converted into a successful result.

The logging callback deliberately avoids recording request headers and response bodies.

5. Example API log output

The example writes one JSON object per line to private/api-requests.jsonl.

This format is commonly called JSON Lines or JSONL.

A successful request might produce:

json
{
 "time": "2026-10-17T07:30:00+00:00",
 "method": "GET",
 "url": "https://api.example.com/products?page=1&limit=20",
 "status": 200,
 "duration_ms": 184
}

The timestamp and duration are illustrative values, not results from a live API test.

A failed HTTP request might return:

json
{
 "time": "2026-10-17T07:31:00+00:00",
 "method": "GET",
 "url": "https://api.example.com/products?page=1&limit=20",
 "status": 500,
 "duration_ms": 206
}

The important advantage is consistency. Every request made through this Guzzle client follows the same logging rules.

JSONL also makes it practical to import logs into a database or analyse them using existing reporting tools.

6. Logging query parameters without exposing API keys

The safeRequestUrl() function deliberately restricts which query parameters are included in the recorded URL.

Only page and limit are approved in this example.

Suppose an API request contains:

text
https://api.example.com/products?page=1&limit=20&api_key=SECRET&customer_email=user@example.com

The logged URL becomes:

text
https://api.example.com/products?page=1&limit=20

This approach uses an allowlist rather than attempting to maintain an incomplete list of sensitive parameter names.

Change the allowlist to match the non-sensitive parameters used by your integration.

Remember that sensitive information can also appear in URL paths. For APIs that embed tokens, customer identifiers or private document references in paths, sanitise those path segments or log a predefined endpoint identifier instead.

Never assume that removing query parameters makes every URL safe to record.

7. Capturing response status codes

The middleware receives the response after the underlying handler completes.

It can therefore record the HTTP status code without consuming the response body.

Typical responses include successful requests, authentication failures, missing resources, rate limits and server errors.

The example sets:

php
<?php
'http_errors' => false,

This tells Guzzle not to turn HTTP responses with 4xx or 5xx status codes into exceptions automatically.

The application can inspect the status code and handle it according to the API's requirements.

This setting does not prevent transport failures, such as connection errors or timeouts, from causing exceptions.

The middleware records those failures separately.

8. Measuring API request duration

The example uses PHP's hrtime() function to measure elapsed time.

The timer starts when the request enters the logging middleware and ends when the corresponding response or rejection is handled.

Duration values are recorded in milliseconds.

This makes it possible to identify integrations that are responding slowly or failing intermittently.

For example, repeated requests taking several seconds might indicate network latency, remote API performance problems or requests waiting for an overloaded service.

Middleware timing is not necessarily identical to the network transfer time. It can include processing performed by components further down the middleware stack.

For transfer-level statistics, Guzzle also supports the on_stats request option.

See the Guzzle on_stats documentation.

9. Handling failed requests and exceptions

A failed connection does not always produce an HTTP response.

DNS failures, connection refusals and timeouts can result in rejected promises instead.

The middleware captures these cases and records the exception class when available.

It does not record the complete exception message by default because messages can contain the requested URL, including sensitive query parameters.

For HTTP errors, the example records the actual status code.

For transport failures, it records a null status and an error type.

These two cases should be distinguished when analysing logs. An HTTP 500 response means the remote server returned a response; a connection failure means the HTTP exchange did not complete normally.

10. Integrating with a custom PHP logging system

Not every application uses Monolog or a PSR-3-compatible logger.

The example intentionally defines logging as a simple callback:

php
<?php
$logEvent = static function (array $event): void {
 // Send the approved event fields to your logging system.
};

You can replace the file-writing implementation with a call to an existing database logger, audit system or internal monitoring service.

The middleware does not need to know how those records are stored.

A custom logger might also attach an internal request identifier, integration name or application module so that related events can be grouped together.

Keep these identifiers separate from credentials and customer data.

The logging callback should handle its own failures. A temporary inability to write diagnostic logs should not unexpectedly prevent an otherwise valid API request from completing.

11. Should you log complete request and response bodies?

For most production integrations, logging metadata is a safer default than recording entire HTTP payloads.

Request bodies may contain passwords, payment information, addresses, personal details or authentication tokens.

Response bodies may contain equally sensitive customer or business information.

Reading response streams inside middleware can also interfere with later application code if the stream position is changed and not restored.

If payload logging is necessary for a specific debugging task, implement explicit redaction, restrict it to approved environments and use controlled retention periods.

Prefer logging response status codes, request identifiers and carefully selected diagnostic fields.

For systems processing personal information, apply the organisation's privacy and data-retention requirements, including relevant POPIA obligations where applicable.

12. Testing the logging middleware

Before deploying, confirm that a successful GET request produces a log entry containing the expected method, approved query parameters, status and duration.

Next, submit a request that produces a 404 or 500 response and verify that the status is recorded without interrupting normal response handling.

Test connection failures and timeouts to confirm that errors are recorded without including sensitive exception messages.

Add an API key or other confidential value to the query string and check that it does not appear in the log.

Also test what happens when the logging directory becomes unwritable.

For automated testing without making external requests, use Guzzle's MockHandler and inspect the recorded events. The Guzzle testing documentation explains how to simulate requests and responses.

Final recommendations

Do not rewrite working Guzzle API calls simply to capture their URLs.

Use the query request option for GET parameters and middleware to observe requests centrally.

Convert the PSR-7 URI to a string when you need its complete value, but sanitise it before recording it in production logs.

A reusable logging middleware should capture the request method, approved URL details, response status, duration and error type while preserving the original HTTP behaviour.

For applications with multiple external integrations, create one consistently configured Guzzle client per integration or share a middleware factory across clients.

This approach is suitable for payment integrations, CRM synchronisation, shipping APIs, ERP systems and other PHP applications that depend on external HTTP services.

For further reading, consult the Guzzle middleware documentation, Guzzle request options and PHP HTTP query-building documentation.

WhatsApp us