Logging external HTTP Requests with Laravel Telescope

Tutorials

July 21st, 2022

Logging external HTTP Requests with Laravel Telescope

The biggest issue with working with third-party APIs is that we have very little visibility. We integrate them into our code base and test them - but we have no idea how often we use them unless the API we are integrating with has metrics we can use. I have been quite frustrated with this for quite some time - but there is something we can do.

Laravel Telescope is a debugging assistant for your application, which means that it will log and give you insight into what is going on from a high level. We can tap into this and add custom watchers to enable more debugging and logging, and this is what we will do in this short tutorial.

Once you have installed Laravel Telescope, make sure you publish the configuration and migrate the database, we can start to create our watcher for Guzzle - the client underneath the Http facade. The most logical place to keep these classes, at least for me, is inside app/Telescope/Watchers as the code belongs to our application - but we are extending Telescope itself. But what does a standard watcher look like? I will show you a rough outline of the base requirements below:

1class YourWatcher extends Watcher
2{
3 public function register($app): void
4 {
5 // handle code for watcher here.
6 }
7}

This is a rough outline. You can add as many methods as you need to add the watcher that works for you. So without further ado, let us create a new watcher app/Telescope/Watchers/GuzzleRequestWatcher.php, and we will walk through what it needs to do.

1declare(strict_types=1);
2 
3namespace App\\Telescope\\Watchers;
4 
5use GuzzleHttp\\Client;
6use GuzzleHttp\\TransferStats;
7use Laravel\\Telescope\\IncomingEntry;
8use Laravel\\Telescope\\Telescope;
9use Laravel\\Telescope\\Watchers\\FetchesStackTrace;
10use Laravel\\Telescope\\Watchers\\Watcher;
11 
12final class GuzzleRequestWatcher extends Watcher
13{
14 use FetchesStackTrace;
15}

We first need to include the trait FetchesStackTrace as this allows us to capture what and where these requests are coming from. If we refactor these HTTP calls to other locations, we can make sure we call them how we intend to. Next, we need to add a method for registering our watcher:

1declare(strict_types=1);
2 
3namespace App\\Telescope\\Watchers;
4 
5use GuzzleHttp\\Client;
6use GuzzleHttp\\TransferStats;
7use Laravel\\Telescope\\IncomingEntry;
8use Laravel\\Telescope\\Telescope;
9use Laravel\\Telescope\\Watchers\\FetchesStackTrace;
10use Laravel\\Telescope\\Watchers\\Watcher;
11 
12final class GuzzleRequestWatcher extends Watcher
13{
14 use FetchesStackTrace;
15 
16 public function register($app)
17 {
18 $app->bind(
19 abstract: Client::class,
20 concrete: $this->buildClient(
21 app: $app,
22 ),
23 );
24 }
25}

We intercept the Guzzle client and register it into the container, but to do so, we want to specify how we want the client to be built. Let’s look at the buildClient method:

1private function buildClient(Application $app): Closure
2{
3 return static function (Application $app): Client {
4 $config = $app['config']['guzzle'] ?? [];
5 
6 if (Telescope::isRecording()) {
7 // Record our Http query.
8 }
9 
10 return new Client(
11 config: $config,
12 );
13 };
14}

We return a static function that builds our Guzzle Client here. First, we get any guzzle config - and then, if telescope is recording, we add a way to record the query. Finally, we return the client with its configuration. So how do we record our HTTP query? Let’s take a look:

1if (Telescope::isRecording()) {
2 $config['on_stats'] = static function (TransferStats $stats): void {
3 $caller = $this->getCallerFromStackTrace(); // This comes from the trait we included.
4 
5 Telescope::recordQuery(
6 entry: IncomingEntry::make([
7 'connection' => 'guzzle',
8 'bindings' => [],
9 'sql' => (string) $stats->getEffectiveUri(),
10 'time' => number_format(
11 num: $stats->getTransferTime() * 1000,
12 decimals: 2,
13 thousand_separator: '',
14 ),
15 'slow' => $stats->getTransferTime() > 1,
16 'file' => $caller['file'],
17 'line' => $caller['line'],
18 'hash' => md5((string) $stats->getEffectiveUri())
19 ]),
20 );
21 };
22}

So we extend the configuration by adding the on_stats option, which is a callback. This callback will get the stack trace and record a new query. This new entry will contain all relevant things to do with the query we can record. So if we put it all together:

1declare(strict_types=1);
2 
3namespace App\Telescope\Watchers;
4 
5use Closure;
6use GuzzleHttp\Client;
7use GuzzleHttp\TransferStats;
8use Illuminate\Foundation\Application;
9use Laravel\Telescope\IncomingEntry;
10use Laravel\Telescope\Telescope;
11use Laravel\Telescope\Watchers\FetchesStackTrace;
12use Laravel\Telescope\Watchers\Watcher;
13 
14final class GuzzleRequestWatcher extends Watcher
15{
16 use FetchesStackTrace;
17 
18 public function register($app): void
19 {
20 $app->bind(
21 abstract: Client::class,
22 concrete: $this->buildClient(
23 app: $app,
24 ),
25 );
26 }
27 
28 private function buildClient(Application $app): Closure
29 {
30 return static function (Application $app): Client {
31 $config = $app['config']['guzzle'] ?? [];
32 
33 if (Telescope::isRecording()) {
34 $config['on_stats'] = function (TransferStats $stats) {
35 $caller = $this->getCallerFromStackTrace();
36 Telescope::recordQuery(
37 entry: IncomingEntry::make([
38 'connection' => 'guzzle',
39 'bindings' => [],
40 'sql' => (string) $stats->getEffectiveUri(),
41 'time' => number_format(
42 num: $stats->getTransferTime() * 1000,
43 decimals: 2,
44 thousands_separator: '',
45 ),
46 'slow' => $stats->getTransferTime() > 1,
47 'file' => $caller['file'],
48 'line' => $caller['line'],
49 'hash' => md5((string) $stats->getEffectiveUri()),
50 ]),
51 );
52 };
53 }
54 
55 return new Client(
56 config: $config,
57 );
58 };
59 }
60}

Now, all we need to do is make sure that we register this new watcher inside of config/telescope.php, and we should start seeing our Http queries being logged.

1'watchers' => [
2 // all other watchers
3 App\\Telescope\\Watchers\\GuzzleRequestWatcher::class,
4]

To test this, create a test route:

1Route::get('/guzzle-test', function () {
2 Http::post('<https://jsonplaceholder.typicode.com/posts>', ['title' => 'test']);
3});

When you open up Telescope, you should now see a navigation item on the side called HTTP Client, and if you open this up, you will see logs appear here - you can inspect the headers, the payload, and the status of the request. So if you start seeing failures from API integrations, this will help you massively with your debugging.

Did you find this helpful? What other ways do you use to monitor and log your external API requests? Let us know on Twitter!