Skip to content
This repository was archived by the owner on May 25, 2021. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 27 additions & 10 deletions src/Trace/Integrations/Guzzle/EventSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@

namespace OpenCensus\Trace\Integrations\Guzzle;

use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Stream\StreamInterface;
use OpenCensus\Core\Scope;
use OpenCensus\Trace\Propagator\ArrayHeaders;
use OpenCensus\Trace\Span;
use OpenCensus\Trace\Tracer;
use OpenCensus\Trace\Propagator\HttpHeaderPropagator;
use OpenCensus\Trace\Propagator\PropagatorInterface;
use GuzzleHttp\Event\BeforeEvent;
Expand Down Expand Up @@ -72,6 +73,7 @@ class EventSubscriber implements SubscriberInterface
*
* @param TracerInterface $tracer
* @param PropagatorInterface $propagator Interface responsible for serializing trace context
* @param bool $logBody Should the body be logged in a span (up to 4096 bytes with Content-Length header set)
*/
public function __construct(TracerInterface $tracer, PropagatorInterface $propagator = null, bool $logBody = true)
{
Expand All @@ -88,8 +90,8 @@ public function __construct(TracerInterface $tracer, PropagatorInterface $propag
public function getEvents()
{
return [
'before' => ['onBefore'],
'end' => ['onEnd']
'before' => ['onBefore'],
'end' => ['onEnd'],
];
}

Expand Down Expand Up @@ -141,6 +143,7 @@ public function onEnd(EndEvent $event)

if ($response === null) {
$this->scope->close();

return;
}

Expand All @@ -153,13 +156,7 @@ public function onEnd(EndEvent $event)
}

if ($this->logBody) {
$bodyLength = (int)$response->getHeader('Content-Length');
if ($bodyLength > 0 && $bodyLength <= 4096) {
$body = (string)$response->getBody();
} else {
$body = 'Either Content-Length is missing, or it is bigger than 4096';
}
$this->span->addAttribute('response.body', $body);
$this->addBody($response);
}

$attrHeaders = [];
Expand All @@ -170,4 +167,24 @@ public function onEnd(EndEvent $event)

$this->scope->close();
}

/**
* @param ResponseInterface $response
*/
private function addBody(ResponseInterface $response)
{
$bodyLength = (int)$response->getHeader('Content-Length');
if ($bodyLength > 0 && $bodyLength <= 4096) {
$body = $response->getBody();
if ($body instanceof StreamInterface && $body->isSeekable()) {
$responseBody = (string)$response->getBody();
$body->seek(0, SEEK_SET);
} else {
$responseBody = 'Response body is not a seekable object';
}
} else {
$responseBody = 'Either Content-Length is missing, or it is bigger than 4096';
}
$this->span->addAttribute('response.body', $responseBody);
}
}