Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: Update GuzzleHttpClientAspect to support transfer methods and enhance request logging #835

Merged
merged 5 commits into from
Feb 7, 2025
66 changes: 35 additions & 31 deletions src/sentry/src/Aspect/GuzzleHttpClientAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@
use FriendsOfHyperf\Sentry\Integration;
use FriendsOfHyperf\Sentry\Switcher;
use GuzzleHttp\Client;
use GuzzleHttp\TransferStats;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Psr\Http\Message\ResponseInterface;
use Sentry\Breadcrumb;

/**
Expand All @@ -26,8 +26,7 @@
class GuzzleHttpClientAspect extends AbstractAspect
{
public array $classes = [
Client::class . '::request',
Client::class . '::requestAsync',
Client::class . '::transfer',
];

public function __construct(protected Switcher $switcher)
Expand All @@ -36,47 +35,52 @@ public function __construct(protected Switcher $switcher)

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
// If the guzzle aspect is disabled, we will not record the request.
if (! $this->switcher->isBreadcrumbEnable('guzzle')) {
return $proceedingJoinPoint->process();
}

$startTime = microtime(true);
$instance = $proceedingJoinPoint->getInstance();
$arguments = $proceedingJoinPoint->arguments;
$options = $arguments['keys']['options'] ?? [];
$guzzleConfig = (fn () => $this->config ?? [])->call($instance);
$options = $proceedingJoinPoint->arguments['keys']['options'] ?? [];
$guzzleConfig = (fn () => match (true) {
method_exists($this, 'getConfig') => $this->getConfig(), // @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
property_exists($this, 'config') => $this->config,
default => [],
})->call($proceedingJoinPoint->getInstance());

// If the no_sentry_aspect option is set to true, we will not record the request.
if (($options['no_sentry_aspect'] ?? null) === true || ($guzzleConfig['no_sentry_aspect'] ?? null) === true) {
return $proceedingJoinPoint->process();
}

// Disable the aspect for the requestAsync method.
if ($proceedingJoinPoint->methodName == 'request') {
$proceedingJoinPoint->arguments['keys']['options']['no_sentry_aspect'] = true;
}
$onStats = $options['on_stats'] ?? null;

$uri = (string) ($arguments['keys']['uri'] ?? '');
$data['config'] = $guzzleConfig;
$data['request']['method'] = $arguments['keys']['method'] ?? 'GET';
$data['request']['options'] = $arguments['keys']['options'] ?? [];
$proceedingJoinPoint->arguments['keys']['options']['on_stats'] = function (TransferStats $stats) use ($onStats, $guzzleConfig, $options) {
$request = $stats->getRequest();
$response = $stats->getResponse();

$result = $proceedingJoinPoint->process();
$uri = $request->getUri()->__toString();
$data = [];
$data['config'] = $guzzleConfig;
$data['request']['method'] = $request->getMethod();
$data['request']['options'] = $options;
$data['response']['status'] = $response?->getStatusCode();
$data['response']['reason'] = $response?->getReasonPhrase();
$data['response']['headers'] = $response?->getHeaders();
$data['duration'] = $stats->getTransferTime() * 1000;

if ($result instanceof ResponseInterface) {
$data['response']['status'] = $result->getStatusCode();
$data['response']['reason'] = $result->getReasonPhrase();
$data['response']['headers'] = $result->getHeaders();
}
$data['timeMs'] = (microtime(true) - $startTime) * 1000;
Integration::addBreadcrumb(new Breadcrumb(
Breadcrumb::LEVEL_INFO,
Breadcrumb::TYPE_DEFAULT,
'guzzle',
$uri,
$data
));

Integration::addBreadcrumb(new Breadcrumb(
Breadcrumb::LEVEL_INFO,
Breadcrumb::TYPE_DEFAULT,
'guzzle',
$uri,
$data
));
if (is_callable($onStats)) {
($onStats)($stats);
}
};

return $result;
return $proceedingJoinPoint->process();
}
}
105 changes: 48 additions & 57 deletions src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@
use FriendsOfHyperf\Sentry\Switcher;
use FriendsOfHyperf\Sentry\Tracing\SpanStarter;
use GuzzleHttp\Client;
use GuzzleHttp\TransferStats;
use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Sentry\SentrySdk;
use Sentry\Tracing\SpanStatus;
use Throwable;

/**
* @method array getConfig()
Expand All @@ -33,8 +32,7 @@
use SpanStarter;

public array $classes = [
Client::class . '::request',
Client::class . '::requestAsync',
Client::class . '::transfer',
];

public function __construct(
Expand All @@ -52,44 +50,25 @@
return $proceedingJoinPoint->process();
}

$instance = $proceedingJoinPoint->getInstance();
$arguments = $proceedingJoinPoint->arguments['keys'];
$uri = (string) ($arguments['uri'] ?? '/');
$method = $arguments['method'] ?? 'GET';
$options = $arguments['options'] ?? [];
$guzzleConfig = (fn () => match (true) {
method_exists($this, 'getConfig') => $this->getConfig(), // @deprecated ClientInterface::getConfig will be removed in guzzlehttp/guzzle:8.0.
property_exists($this, 'config') => $this->config,
default => [],
})->call($instance);
})->call($proceedingJoinPoint->getInstance());

// If the no_sentry_tracing option is set to true, we will not record the request.
if (
($options['no_sentry_tracing'] ?? null) === true
|| ($guzzleConfig['no_sentry_tracing'] ?? null) === true
) {
return $proceedingJoinPoint->process();
}

// Disable the aspect for the requestAsync method.
if ($proceedingJoinPoint->methodName == 'request') {
$proceedingJoinPoint->arguments['keys']['options']['no_sentry_tracing'] = true;
}

$uri = (string) ($arguments['uri'] ?? '/');
$method = $arguments['method'] ?? 'GET';
$fullUri = new \GuzzleHttp\Psr7\Uri($uri);

$data = [
// See: https://develop.sentry.dev/sdk/performance/span-data-conventions/#http
'http.query' => $fullUri->getQuery(),
'http.fragment' => $fullUri->getFragment(),
'http.request.method' => $method,
'http.request.body.size' => strlen($arguments['options']['body'] ?? ''),
// Other
'coroutine.id' => Coroutine::id(),
'http.system' => 'guzzle',
'http.guzzle.config' => $guzzleConfig,
'http.guzzle.options' => $arguments['options'] ?? [],
];

// Inject trace context
$parent = SentrySdk::getCurrentHub()->getSpan();
$options['headers'] = array_replace($options['headers'] ?? [], [
'sentry-trace' => $parent->toTraceparent(),
Expand All @@ -98,44 +77,56 @@
]);
$proceedingJoinPoint->arguments['keys']['options']['headers'] = $options['headers'];

// Start span
$span = $this->startSpan('http.client', $method . ' ' . (string) $uri);

try {
$result = $proceedingJoinPoint->process();
if (! $span) {
return $proceedingJoinPoint->process();
}

if (! $span) {
return $result;
$onStats = $options['on_stats'] ?? null;

$proceedingJoinPoint->arguments['keys']['options']['on_stats'] = function (TransferStats $stats) use ($arguments, $guzzleConfig, $onStats, $span) {
$request = $stats->getRequest();
$response = $stats->getResponse();
$uri = $request->getUri();
$method = $request->getMethod();
$statusCode = $response->getStatusCode();
$data = [
// See: https://develop.sentry.dev/sdk/performance/span-data-conventions/#http
'http.query' => $uri->getQuery(),
'http.fragment' => $uri->getFragment(),
'http.request.method' => $method,
'http.request.body.size' => strlen($arguments['options']['body'] ?? ''),
// Other
'coroutine.id' => Coroutine::id(),
'http.system' => 'guzzle',
'http.guzzle.config' => $guzzleConfig,
'http.guzzle.options' => $arguments['options'] ?? [],
'duration' => $stats->getTransferTime() * 1000, // in milliseconds
'response.status' => $statusCode,
'response.reason' => $response->getReasonPhrase(),
'response.headers' => $response->getHeaders(),
];

if ($this->switcher->isTracingExtraTagEnable('response.body')) {
$data['response.body'] = $response->getBody()->getContents();
$response->getBody()->isSeekable() && $response->getBody()->rewind();
}

if ($result instanceof ResponseInterface) {
$data += [
'response.status' => $result->getStatusCode(),
'response.reason' => $result->getReasonPhrase(),
'response.headers' => $result->getHeaders(),
];
if ($this->switcher->isTracingExtraTagEnable('response.body')) {
$data['response.body'] = $result->getBody()->getContents();
$result->getBody()->rewind();
}
}
} catch (Throwable $exception) {
$span->setStatus(SpanStatus::internalError());
$span->setTags([
'error' => true,
'exception.class' => $exception::class,
'exception.message' => $exception->getMessage(),
'exception.code' => $exception->getCode(),
]);
if ($this->switcher->isTracingExtraTagEnable('exception.stack_trace')) {
$data['exception.stack_trace'] = (string) $exception;
if ($statusCode >= 400 && $statusCode < 600) {
$span->setStatus(SpanStatus::internalError());
$span->setTags(['error' => true]);

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.3 with Swoole 5.1.6

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.3 with Swoole 6.0.0

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.2 with Swoole 5.1.6

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.2 with Swoole 6.0.0

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.1 with Swoole 5.1.6

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.1 with Swoole 6.0.0

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.3 with Swoole 5.1.6

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.3 with Swoole 6.0.0

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.2 with Swoole 5.1.6

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.2 with Swoole 6.0.0

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.1 with Swoole 5.1.6

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.

Check failure on line 119 in src/sentry/src/Tracing/Aspect/GuzzleHttpClientAspect.php

View workflow job for this annotation

GitHub Actions / Test on PHP 8.1 with Swoole 6.0.0

Parameter #1 $tags of method Sentry\Tracing\Span::setTags() expects array<string, string>, array<string, true> given.
}

throw $exception;
} finally {
$span->setData($data);
$span->finish();
}

return $result;
if (is_callable($onStats)) {
($onStats)($stats);
}
};

return $proceedingJoinPoint->process();
}
}
Loading