CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

25 August, 2022

Logging external HTTP Requests with Laravel Telescope

 Programing Coderfunda     August 25, 2022     Laravel, Laravel Tutorials, Packages     No comments   

 

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!

  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • SON API Resources in Laravel Building APIs in Laravel is a passion of mine, and I have spent a lot of time searching for the perfect way to return consistent JSON:API friend… Read More
  • How I develop applications with Laravel I get asked a lot about how you work with Laravel. So in this tutorial, I will walk through my typical approach to building a Laravel applicatio… Read More
  • Building your own Laravel PackagesSharing code has never been more accessible, and installing PHP packages has become convenient; building packages however? In this tutorial, I will wa… Read More
  • Using Laravel Model Factories in your testsLaravel Model factories are one of the best features you can use in your application when it comes to testing. They provide a way to define data that … Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...
  • SQL ORDER BY Keyword
      The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts ...
  • Enabling authentication in swagger
    I created a asp.net core empty project running on .net6. I am coming across an issue when I am trying to enable authentication in swagger. S...
  • failed to load storage framework cache laravel excel
       User the export file and controller function  ..         libxml_use_internal_errors ( true ); ..Good To Go   public function view () : ...
  • AdminJS not overriding default dashboard with custom React component
    So, I just started with adminjs and have been trying to override the default dashboard with my own custom component. I read the documentatio...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Efficiently remove expired cache data with Laravel Cache Evict - 6/3/2025
  • Test Job Failures Precisely with Laravel's assertFailedWith Method - 5/31/2025
  • Prism Relay - 6/2/2025
  • Enhance Collection Validation with containsOneItem() Closure Support - 5/31/2025
  • Filament Is Now Running Natively on Mobile - 5/31/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda