Guzzle4: Recording the time of an API Call

38 views
Skip to first unread message

J Cobb

unread,
May 27, 2014, 3:40:40 PM5/27/14
to guz...@googlegroups.com
I'd like to be able to record the amount of time that it takes for an API Call to be sent and the full response to be received.

I was thinking this should be an Event Listener or Subscriber but I am having trouble figuring out how to attach one since I am also using a ClientFactory with a Service Description and all of the examples of adding subscribers/listeners seem to do so directly on the $client and I can't figure out how to access the client when using the Service Description. Additionally, I'm not sure how I would access the elapsed time after the call is complete.

Here is what I had started with, but I was unable to figure out how to actually get everything working. Any help is appreciated.

class RequestTimer implements SubscriberInterface
{
    /** @var float Used to measure API call execution time */
    protected $_timeStart;
    protected $_timeEnd;


    public function __construct(Configuration $config)
    {
        $this->config = $config;
    }


    public function getEvents()
    {
        return [
            'before' => ['_startTimer', (RequestEvents::SIGN_REQUEST - 1)],
            'after'  => ['_endTimer', (RequestEvents::EARLY + 1),
                '_getElapsedTime', (RequestEvents::EARLY + 2)],
        ];
    }


    protected function _startTimer(BeforeEvent $event)
    {
        $this->_timeStart = microtime(true);
    }


    protected function _endTimer(CompleteEvent $event)
    {
        $this->_timeEnd = microtime(true);
    }


    protected function _getElapsedTime()
    {
        try {
            return $this->_timeEnd - $this->_timeStart;
        } catch (\Exception $e) {
            return false;
        }
    }


}
Reply all
Reply to author
Forward
0 new messages