10

目前使用 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();
4

2 回答 2

4

我向您推荐“on_stats”请求选项Guzzle Docs - Request OptionsTransferStats 对象

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

// 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是在各个处理程序中生成和使用的,此时处理程序不能将其提供给堆栈。因此,它们不能在放置在堆栈上的各个中间件中使用。

于 2015-09-23T15:33:16.627 回答
0

I don't have enough reputation to comment but just to improve this answer

$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);
    },
]);

P.S.: This code is for Guzzle 7

于 2020-11-05T12:20:04.670 回答