目前,在Guize6中,似乎没有现成的方法来获取API调用的持续时间。使用下面的代码,通过任何普通调用获取此统计数据的最佳方式是什么?
我使用How do you log all API calls using Guzzle 6中的以下代码
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();发布于 2015-09-23 23:33:17
我建议您参考'on_stats‘请求选项Guzzle Docs - Request Options和TransferStats object
要实现这一点,您需要修改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是在各个处理程序中生成和使用的,此时处理程序不能用于堆栈。因此,它们不能在放置在堆栈上的独立中间件中使用。
发布于 2020-11-05 20:20:05
我没有足够的名气来评论,但只是为了改善this的答案
$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);
},
]);附言:这段代码是为Guzzle 7编写的
https://stackoverflow.com/questions/32727640
复制相似问题