使用Guzzle 6获取API调用持续时间的最佳方法是什么

Kin*_*rog 10 php guzzle guzzle6

目前使用Guzzle 6似乎没有开箱即用的方式来获得API调用的持续时间.使用下面的代码,通过任何普通电话获得此统计数据的最佳方法是什么.

我正在使用以下代码如何使用Guzzle 6记录所有API调用

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();
Run Code Online (Sandbox Code Playgroud)

Sha*_*ley 4

我建议您参考“on_stats”请求选项Guzzle Docs - 请求选项TransferStats 对象

要实现此目的,您需要修改您的获取请求以使用请求选项。它会像下面这样:

// get($uri, $options) proxies to request($method, $uri, $options)
// request($method, $uri, $options) proxies to requestAsync($method, $uri, $options)
// and sets the $options[RequestOptions::SYNCHRONOUS] to true
// and then waits for promises to resolve returning a Psr7\http-message\ResponseInterface instance

$response = $client->get($uri, [
    'on_stats'  => function (TransferStats $stats) use ($logger) {
        // do something inside the callable.
        echo $stats->getTransferTime() . "\n";
        $logger->debug('Request' . $stats->getRequest() . 
                       'Response' . $stat->getResponse() .
                       'Tx Time' . $stat->getTransferTime()
        );
    },
]);
echo $response->getBody();
Run Code Online (Sandbox Code Playgroud)

**注意:我确信有一些方法可以确保日志的格式更好,但是,这是作为概念证明。

它们TransferStats是在各个处理程序内生成和使用的,此时处理程序无法将其提供给堆栈。因此,它们无法在堆栈上的各个中间件中使用。

  • 我仍然不明白如何将传输时间发送到处理程序,以便它可以在相同的输出中?例如:`new MessageFormatter('{req_body} - {res_body} - {REQUEST_TIME}')` (2认同)