Skip to content

Instantly share code, notes, and snippets.

@Caffe1neAdd1ct
Last active June 19, 2018 09:35
Show Gist options
  • Save Caffe1neAdd1ct/0fec796eee4ef60bdc2f9df70252a5d6 to your computer and use it in GitHub Desktop.
Save Caffe1neAdd1ct/0fec796eee4ef60bdc2f9df70252a5d6 to your computer and use it in GitHub Desktop.
Guzzle 6.3.3 logging to console
<?php
require_once 'vendor/autoload.php';
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Client;
use Concat\Http\Middleware\Logger;
/** Guzzle logging setup */
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$middleware = new Logger(function ($level, $message, array $context) {
$o = function($str) { echo $str . PHP_EOL; };
$h = function($request) {
/* @var $request Request */
$headerStr = "";
foreach (array_keys($request->getHeaders()) as $header) {
/* @var $request Request */
$headerStr .= $header . ', ' . $request->getHeaderLine($header) . PHP_EOL;
}
return $headerStr;
};
/* @var $request GuzzleHttp\Psr7\Request */
$request = $context['request'];
/* @var $response GuzzleHttp\Psr7\Response */
$response = $context['response'];
if(!$response) {
$o(PHP_EOL . 'REQUEST - ' . strtoupper($level) . ' - ' . $request->getMethod());
$o($message);
$o($h($request));
$o($request->getUri());
$o($request->getRequestTarget());
$o('CONTENT - ' . $request->getBody()->getContents());
} else {
$o(PHP_EOL . 'RESPONSE - ' . strtoupper($level) . ' - ' . $response->getStatusCode());
$o($message);
$o($h($response));
$o('CONTENT - ' . $response->getBody()->getContents());
$o($response->getReasonPhrase());
$response->getBody()->rewind();
}
});
$middleware->setRequestLoggingEnabled(true);
$stack->push($middleware);
$client = new Client(['handler' => $stack]);
{
"name": "my/project",
"description": "Description of project.",
"authors": [
{
"name": "yourname",
"email": "your@email.here"
}
],
"require": {
"php": ">=5.5",
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
"guzzlehttp/guzzle": "^6.2",
"symfony/polyfill-mbstring": "1.8.0",
"rtheunissen/guzzle-log-middleware": "^0.4.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment