guzzle/plugin-log
Adds logging to Guzzle HTTP requests and responses via a plugin/listener. Capture and format request/response headers, bodies, and timing to help debug API calls, trace issues, and record activity to PSR-3 logs or custom handlers.
Installation Add the package via Composer:
composer require guzzle/plugin-log
(Note: This is a Guzzle 3 plugin—ensure compatibility with your Laravel version if using Guzzle 3.)
Basic Usage Attach the logging plugin to a Guzzle client:
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Plugin\Log\StreamHandler;
$client = new \Guzzle\Http\Client();
$client->getPlugin('log')->setHandler(new StreamHandler('php://output'));
$client->getPlugin('log')->setEnabled(true);
First Use Case Debug API requests/responses in real-time:
$response = $client->get('https://api.example.com/data');
// Logs request/response to stdout.
Request/Response Logging Log all requests/responses to a file or stream:
$client->getPlugin('log')->setHandler(new StreamHandler(fopen('debug.log', 'a')));
Conditional Logging Enable logging only for specific environments:
if (app()->environment('local')) {
$client->getPlugin('log')->setEnabled(true);
}
Custom Formatting Extend the default logger to include Laravel-specific data (e.g., request IDs):
$logger = new class implements \Psr\Log\LoggerInterface {
public function log($level, $message, array $context = []) {
// Prepend Laravel request ID.
$context['request_id'] = request()->id();
// Delegate to Guzzle's logger.
}
};
Integration with Laravel Logging Route Guzzle logs to Laravel’s log channel:
use Illuminate\Support\Facades\Log;
$client->getPlugin('log')->setHandler(new class {
public function write($message) {
Log::debug($message);
}
});
Guzzle 3 Compatibility
composer require guzzlehttp/guzzle
And use GuzzleHttp\HandlerStack with middleware instead.Performance Overhead
$client->getPlugin('log')->setEnabled(env('APP_DEBUG'));
Sensitive Data Leaks
$handler = new class {
public function write($message) {
$message = str_replace('password=.*&', 'password=***&', $message);
Log::debug($message);
}
};
Handler Quirks
StreamHandler may block if writing to a slow resource (e.g., network share).Psr\Log\LoggerInterface handlers for better integration.if (!$client->hasPlugin('log')) {
throw new \RuntimeException('Log plugin not attached!');
}
stderr for Laravel Tinker:
$client->getPlugin('log')->setHandler(new StreamHandler('php://stderr'));
Custom Log Formatters
Override Guzzle\Plugin\Log\MessageFormatter to modify output:
$formatter = new class extends \Guzzle\Plugin\Log\MessageFormatter {
protected function formatRequest(\Guzzle\Http\Message\Request $request) {
return "[CUSTOM] " . parent::formatRequest($request);
}
};
$client->getPlugin('log')->setFormatter($formatter);
Async Logging Use a queueable handler for high-throughput systems:
$handler = new class {
public function write($message) {
LogRequest::dispatch($message);
}
};
How can I help you explore Laravel packages today?