【问题标题】:What's the best way to get the duration of an API call using Guzzle 6使用 Guzzle 6 获取 API 调用持续时间的最佳方法是什么
【发布时间】:2015-12-20 01:36:12
【问题描述】:

目前使用 Guzzle 6,似乎没有开箱即用的方法来获取 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();

【问题讨论】:

    标签: php guzzle guzzle6


    【解决方案1】:

    我建议您参考“on_stats”请求选项Guzzle Docs - Request OptionsTransferStats object

    要实现这一点,您需要修改获取请求以使用请求选项。应该是这样的:

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

    【讨论】:

    • 知道如何使用上面的代码来实现传输统计吗?
    • 我仍然不明白如何将传输时间发送到处理程序,以便它可以在同一个输出中?例如:new MessageFormatter('{req_body} - {res_body} - {REQUEST_TIME}')
    【解决方案2】:

    我没有足够的声誉发表评论,只是为了改进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);
        },
    ]);
    

    P.S.:此代码适用于 Guzzle 7

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      相关资源
      最近更新 更多