Created
November 10, 2020 12:18
-
-
Save kobus1998/585e99f77285f9dfda5d7a9218b755d2 to your computer and use it in GitHub Desktop.
log all outgoing requests using guzzle's handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"guzzlehttp/guzzle": "^6.5", | |
"monolog/monolog": "^1.25" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require __DIR__ . '/vendor/autoload.php'; | |
use GuzzleHttp\Client; | |
use GuzzleHttp\HandlerStack; | |
use Monolog\Logger; | |
use Monolog\Handler\StreamHandler; | |
$logger = new Logger('responses'); //initialize the logger | |
$logger->pushHandler(new StreamHandler(__DIR__ . '/dist/text.log', Logger::DEBUG)); | |
$handler = HandlerStack::create(); | |
$handler->push(new LoggingMiddleware($logger), 'logger'); | |
$client = new Client(['handler' => $handler]); //initialize a Guzzle client | |
$response = $client->post('https://postman-echo.com/post', [ // use postman test service to send a request | |
'headers' => [ | |
'content-type' => 'application/json' | |
], | |
'body' => json_encode(['foo' => 'bar']) | |
]); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Psr\Http\Message\RequestInterface; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Log\LoggerInterface; | |
class LoggingMiddleware | |
{ | |
/** @var LoggerInterface */ | |
private $logger; | |
/** | |
* construct | |
* | |
* @param LoggerInterface $logger | |
*/ | |
public function __construct(LoggerInterface $logger) | |
{ | |
$this->logger = $logger; | |
} | |
/** | |
* invoke class | |
* | |
* @param callable $handler | |
* @return callable | |
*/ | |
public function __invoke(callable $handler) | |
{ | |
return function (RequestInterface $request, $options) use ($handler) { // return a callable | |
$promise = $handler($request, $options); // get the new handler | |
return $promise->then(function (ResponseInterface $response) use ($request) { // add a new promise which is a callback after response has been received | |
$this->logger->info(print_r([ | |
'method' => (string) $request->getMethod(), | |
'url' => (string) $request->getUri(), | |
'response' => (string) $response->getBody(), | |
'request' => (string) $request->getBody() | |
], true)); | |
return $response; | |
}); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment