如何使用 Guzzle 6 记录所有 API 次调用

How do you log all API calls using Guzzle 6

我正在尝试使用 guzzle 6,它运行良好,但我不知道如何记录所有 api 调用。我想简单地记录时间、从会话中登录的用户、url 以及与 API 调用有关的任何其他常见相关信息。我似乎找不到 Guzzle 6 的任何文档提到这个,只有 guzzle 3(他们改变了日志记录 addSubscriber 调用)。这就是我目前的 API 通话情况:

$client = new GuzzleHttp\Client(['defaults' => ['verify' => false]]);
$res = $client->get($this->url . '/api/details', ['form_params' => ['file' => $file_id]]);

您可以使用任何实现 PSR-3 接口的记录器与 Guzzle 6

在下面的示例中,我使用 Monolog 作为记录器和 Guzzle 的内置中间件以及 MessageFormatter。

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();

关于日志中间件和消息格式化程序的细节还没有很好的记录。但是你可以 check the list 在 MessageFormatter

中可以使用哪些变量

还有一个 guzzle-logmiddleware 允许您自定义格式化程序等

@KingKongFrog 这是指定日志文件名称的方式

$logger = new Logger('MyLog');
$logger->pushHandler(new StreamHandler(__DIR__ . '/test.log'), Logger::DEBUG);

$stack->push(Middleware::log(
$logger,
new MessageFormatter('{req_body} - {res_body}')
));

对于 Guzzle 7 我这样做了::

require './guzzle_7.2.0.0/vendor/autoload.php';
require './monolog/vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

use GuzzleHttp\MessageFormatter;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

use GuzzleHttp\TransferStats;

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$logger = null;
$messageFormat = 
            //['REQUEST: ', 'METHOD: {method}', 'URL: {uri}', 'HTTP/{version}', 'HEADERS: {req_headers}', 'Payload: {req_body}', 'RESPONSE: ', 'STATUS: {code}', 'BODY: {res_body}'];
            'REQUEST: urldecode(req_body)';
$handlerStack = \GuzzleHttp\HandlerStack::create(); 
$handlerStack->push(createGuzzleLoggingMiddleware($messageFormat));
function getLogger() {
    global $logger;
    if ($logger==null) {
        $logger = new Logger('api-consumer');
        $logger->pushHandler(new \Monolog\Handler\RotatingFileHandler('./TataAigHealthErrorMiddlewarelog.txt'));
    }
    var_dump($logger);
    return $logger;
    }
function createGuzzleLoggingMiddleware(string $messageFormat){
    return \GuzzleHttp\Middleware::log(getLogger(), new \GuzzleHttp\MessageFormatter($messageFormat));
}

function createLoggingHandlerStack(array $messageFormats){  
    global $logger;
    $stack = \GuzzleHttp\HandlerStack::create();
    var_dump($logger);
    collect($messageFormats)->each(function ($messageFormat) use ($stack) {
        // We'll use unshift instead of push, to add the middleware to the bottom of the stack, not the top
        $stack->unshift(createGuzzleLoggingMiddleware($messageFormat) );
    });
    return $stack;
}
//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

$client = new Client(['verify' => false, 'handler' => $tapMiddleware($handlerStack)]);

哇!!