Instrument HTTP Requests

Learn how to manually instrument your code to use Sentry's Requests module.

Sentry offers a requests monitoring dashboard that can be auto-instrumented by our Laravel SDK and Symfony SDK.

If you're using something else, you can manually instrument your requests and use Sentry to get a look into how your requests to APIs are performing by following the setup instructions below.

Make sure that there's a transaction running when you create the spans. See Tracing for more information.

For detailed information about which data can be set, see the Requests Module developer specifications and HTTP Span Data Conventions.

If you're using Guzzle, you can inject Sentry's GuzzleTracingMiddleware into your HandlerStack.

Copied
$stack = new \GuzzleHttp\HandlerStack();
$stack->setHandler(new \GuzzleHttp\Handler\CurlHandler());
$stack->push(\Sentry\Tracing\GuzzleTracingMiddleware::trace());

$client = new \GuzzleHttp\Client(['handler' => $stack]);
$response = $client->get('https://example.com/');

Here is an example of an instrumenting a HTTP request:

Copied
$parentSpan = \Sentry\SentrySdk::getCurrentHub()->getSpan();

if ($parentSpan !== null) {
    $context = \Sentry\Tracing\SpanContext::make()
        ->setOp('http.client');
    $span = $parentSpan->startChild($context);

    // Set the span we just started as the current span
    \Sentry\SentrySdk::getCurrentHub()->setSpan($span);
    
    $client = new \Cake\Http\Client();
    $response = $client->get('https://example.com/');
    
    $span
        ->setDescription('GET https://example.com/')
        ->setStatus(\Sentry\Tracing\SpanStatus::createFromHttpStatusCode($response->getStatusCode()))
        ->setData([
            'http.request.method' => 'GET',
            'http.response.body.size' => $response->getBody()->getSize(),
            'http.response.status_code' => $response->getStatusCode(),
        ])
        ->finish();

    // Restore the span back to the parent span
    \Sentry\SentrySdk::getCurrentHub()->setSpan($parentSpan);
}
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").