Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you log all API calls using Guzzle 6

Tags:

I'm trying to use guzzle 6 which works fine but I'm lost when it comes to how to log all the api calls. I would like to simply log timing, logged in user from session, url and any other usual pertinent info that has to do with the API call. I can't seem to find any documentation for Guzzle 6 that refers to this, only guzzle 3 (Where they've changed the logging addSubscriber call). This is how my current API calls are:

$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]); $res = $client->get($this->url . '/api/details', ['form_params' => ['file' => $file_id]]); 
like image 283
KingKongFrog Avatar asked Sep 20 '15 15:09

KingKongFrog


People also ask

How do I send HTTP request using guzzle?

Sending Requests You can create a request and then send the request with the client when you're ready: use GuzzleHttp\Psr7\Request; $request = new Request('PUT', 'http://httpbin.org/put'); $response = $client->send($request, ['timeout' => 2]);

What is the difference between cURL and guzzle?

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. cURL can be classified as a tool in the "File Transfer" category, while Guzzle is grouped under "Microframeworks (Backend)". cURL and Guzzle are both open source tools.

What GuzzleHttp 7?

Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP responses. Both requests and responses are referred to as messages. Guzzle relies on the guzzlehttp/psr7 Composer package for its message implementation of PSR-7.


2 Answers

You can use any logger which implements PSR-3 interface with Guzzle 6

I used Monolog as logger and builtin middleware of Guzzle with MessageFormatter in below example.

use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\MessageFormatter; use Monolog\Logger;  $stack = HandlerStack::create(); $stack->push(     Middleware::log(         new Logger('Logger'),         new MessageFormatter('{req_body} - {res_body}')     ) ); $client = new \GuzzleHttp\Client(     [         'base_uri' => 'http://httpbin.org',         'handler' => $stack,     ] );  echo (string) $client->get('ip')->getBody(); 

The details about the log middleware and message formatter has not well documented yet. But you can check the list which variables you can use in MessageFormatter

Also there is a guzzle-logmiddleware which allows you to customize formatter etc.

like image 151
velioglu Avatar answered Sep 26 '22 00:09

velioglu


@KingKongFrog This is the way to specify the name of the log file

$logger = new Logger('MyLog'); $logger->pushHandler(new StreamHandler(__DIR__ . '/test.log'), Logger::DEBUG);  $stack->push(Middleware::log( $logger, new MessageFormatter('{req_body} - {res_body}') )); 
like image 21
anhduc.bkhn Avatar answered Sep 23 '22 00:09

anhduc.bkhn