如何用Laravel Telescope记录外部HTTP请求

297 阅读3分钟

与第三方API合作的最大问题是,我们的可见度很低。我们把它们集成到我们的代码库中,并对它们进行测试--但我们不知道我们使用它们的频率,除非我们正在集成的API有我们可以使用的指标。我对这个问题已经感到很沮丧了 - 但是我们可以做一些事情。

Laravel Telescope是你的应用程序的调试助手, 这意味着它将记录并让你从高层次上洞察到正在发生的事情。我们可以利用这一点,添加自定义的观察器,以实现更多的调试和记录,这就是我们在这个简短的教程中要做的。

一旦你安装了Laravel Telescope, 确保你发布了配置并迁移了数据库, 我们就可以开始为Guzzle创建我们的观察器 - Http facade下面的客户端.最合理的地方是保留这些类,至少对我来说,是在app/Telescope/Watchers ,因为这些代码属于我们的应用程序 - 但我们正在扩展Telescope本身。但是一个标准的观察者是什么样子的呢?我将在下面向你展示一个基本要求的粗略轮廓。

class YourWatcher extends Watcher
{
  public function register($app): void
  {
    // handle code for watcher here.
  }
}

这只是一个粗略的轮廓。你可以根据你的需要来添加适合你的观察者的方法。所以不用多说,让我们创建一个新的观察者app/Telescope/Watchers/GuzzleRequestWatcher.php ,我们将走过它需要做什么。

declare(strict_types=1);
 
namespace App\\Telescope\\Watchers;
 
use GuzzleHttp\\Client;
use GuzzleHttp\\TransferStats;
use Laravel\\Telescope\\IncomingEntry;
use Laravel\\Telescope\\Telescope;
use Laravel\\Telescope\\Watchers\\FetchesStackTrace;
use Laravel\\Telescope\\Watchers\\Watcher;
 
final class GuzzleRequestWatcher extends Watcher
{
  use FetchesStackTrace;
}

我们首先需要包括FetchesStackTrace这个特性,因为这可以让我们捕捉到这些请求的来源和位置。如果我们将这些HTTP调用重构到其他地方,我们可以确保我们是按照我们的意图来调用它们。接下来,我们需要添加一个方法来注册我们的观察者。

 declare(strict_types=1);
 
namespace App\\Telescope\\Watchers;
 
use GuzzleHttp\\Client;
use GuzzleHttp\\TransferStats;
use Laravel\\Telescope\\IncomingEntry;
use Laravel\\Telescope\\Telescope;
use Laravel\\Telescope\\Watchers\\FetchesStackTrace;
use Laravel\\Telescope\\Watchers\\Watcher;
 
final class GuzzleRequestWatcher extends Watcher
{
  use FetchesStackTrace;
 
  public function register($app)
  {
    $app->bind(
      abstract: Client::class,
      concrete: $this->buildClient(
        app: $app,
      ),
    );
  }
}

我们拦截Guzzle客户端并将其注册到容器中,但要做到这一点,我们要指定我们希望客户端如何被构建。让我们来看看buildClient方法。

private function buildClient(Application $app): Closure
{
  return static function (Application $app): Client {
      $config = $app['config']['guzzle'] ?? [];
 
    if (Telescope::isRecording()) {
      // Record our Http query.
    }
 
    return new Client(
      config: $config,
    );
  };
}

我们在这里返回一个静态函数来构建我们的Guzzle客户端。首先,我们得到任何guzzle的配置--然后,如果telescope正在记录,我们就添加一个记录查询的方法。最后,我们返回带有配置的客户端。那么我们如何记录我们的HTTP查询呢?让我们来看看。

if (Telescope::isRecording()) {
  $config['on_stats'] = static function (TransferStats $stats): void {
    $caller = $this->getCallerFromStackTrace(); // This comes from the trait we included.
 
    Telescope::recordQuery(
      entry: IncomingEntry::make([
        'connection' => 'guzzle',
        'bindings' => [],
        'sql' => (string) $stats->getEffectiveUri(),
        'time' => number_format(
          num: $stats->getTransferTime() * 1000,
          decimals: 2,
          thousand_separator: '',
        ),
        'slow' => $stats->getTransferTime() > 1,
        'file' => $caller['file'],
        'line' => $caller['line'],
        'hash' => md5((string) $stats->getEffectiveUri())
      ]),
    );
  };
}

所以我们通过添加on_stats 选项来扩展配置,这是一个回调。这个回调将获得堆栈跟踪并记录一个新的查询。这个新条目将包含所有与我们可以记录的查询有关的东西。所以,如果我们把这一切放在一起。

declare(strict_types=1);
 
namespace App\Telescope\Watchers;
 
use Closure;
use GuzzleHttp\Client;
use GuzzleHttp\TransferStats;
use Illuminate\Foundation\Application;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use Laravel\Telescope\Watchers\FetchesStackTrace;
use Laravel\Telescope\Watchers\Watcher;
 
final class GuzzleRequestWatcher extends Watcher
{
    use FetchesStackTrace;
 
    public function register($app): void
    {
        $app->bind(
            abstract: Client::class,
            concrete: $this->buildClient(
                app: $app,
            ),
        );
    }
 
    private function buildClient(Application $app): Closure
    {
        return static function (Application $app): Client {
            $config = $app['config']['guzzle'] ?? [];
 
            if (Telescope::isRecording()) {
                $config['on_stats'] = function (TransferStats $stats) {
                    $caller = $this->getCallerFromStackTrace();
                    Telescope::recordQuery(
                        entry: IncomingEntry::make([
                            'connection' => 'guzzle',
                            'bindings' => [],
                            'sql' => (string) $stats->getEffectiveUri(),
                            'time' => number_format(
                                num: $stats->getTransferTime() * 1000,
                                decimals: 2,
                                thousands_separator: '',
                            ),
                            'slow' => $stats->getTransferTime() > 1,
                            'file' => $caller['file'],
                            'line' => $caller['line'],
                            'hash' => md5((string) $stats->getEffectiveUri()),
                        ]),
                    );
                };
            }
 
            return new Client(
                config: $config,
            );
        };
    }
}

现在,我们需要做的就是确保我们在config/telescope.php 内注册这个新的观察者,我们应该开始看到我们的Http查询被记录下来。

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

为了测试这个,创建一个测试路由。

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

当你打开Telescope时,你现在应该看到一个名为HTTP客户端的导航项,如果你打开它,你会看到日志出现在这里--你可以检查头信息、有效载荷和请求的状态。因此,如果你开始看到API集成的失败,这将极大地帮助你进行调试。