Php 什么';这是使用Guzzle 6获得API调用持续时间的最佳方法

Php 什么';这是使用Guzzle 6获得API调用持续时间的最佳方法,php,guzzle,guzzle6,Php,Guzzle,Guzzle6,目前Guzzle 6似乎没有现成的方法来获取API调用的持续时间。使用下面的代码,通过任何普通调用获取此统计数据的最佳方法是什么 我正在使用来自的以下代码 我建议您参考“on_stats”请求选项 和 要实现这一点,您需要修改get请求以使用请求选项。它将类似于以下内容: // get($uri, $options) proxies to request($method, $uri, $options) // request($method, $uri, $options) proxies to

目前Guzzle 6似乎没有现成的方法来获取API调用的持续时间。使用下面的代码,通过任何普通调用获取此统计数据的最佳方法是什么

我正在使用来自的以下代码


我建议您参考“on_stats”请求选项 和

要实现这一点,您需要修改get请求以使用请求选项。它将类似于以下内容:

// 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();
**注意:我确信有一些方法可以确保日志的格式更好,但是,这只是一个概念证明


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

我没有足够的声誉发表评论,只是为了改进答案


备注:此代码适用于Guzzle 7

您知道如何使用上述代码来实现传输统计信息吗?我仍然不知道如何将传输时间发送给处理程序,使其处于相同的输出中?例如:
newmessageformatter({req\u body}-{res\u body}-{REQUEST\u TIME}')
// 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();
$response = $client->post($uri, [
    RequestOptions::JSON => $postData,
    RequestOptions::ON_STATS => function (TransferStats $stats) use ($logger) {
        $formatter = new MessageFormatter('{"request":{"uri":"{uri}","body":{req_body}},"response":{"code":{code},"body":{res_body}},"time":'.$stats->getTransferTime().'}');
        $message = $formatter->format($stats->getRequest(), $stats->getResponse());

        $logger->info($message);
    },
]);