使用Laravel Telescope记录外部HTTP请求

2023-06-01 laravel 请求 记录

使用第三方API的最大问题是我们的可见性非常低。我们将它们集成到我们的代码库中并对其进行测试——但我们不知道我们使用它们的频率,除非我们集成的 API 具有我们可以使用的指标。很长一段时间以来,我一直对此感到非常沮丧——但我们可以做一些事情。


Laravel Telescope 是您的应用程序的调试助手,这意味着它将记录并让您从高层次了解正在发生的事情。我们可以利用这一点并添加自定义观察程序以启用更多调试和日志记录,这就是我们将在这个简短教程中所做的事情。


一旦你安装了 Laravel Telescope,确保你发布了配置并迁移了数据库,我们就可以开始为 Guzzle 创建我们的 watcher——Http 门面下的客户端。至少对我来说,保存这些类最合乎逻辑的地方是在内部app/Telescope/Watchers,因为代码属于我们的应用程序——但我们正在扩展 Telescope 本身。

但是标准的观察者是什么样的呢?

我将向您展示以下基本要求的大致轮廓:

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

这是一个粗略的轮廓。您可以根据需要添加任意数量的方法来添加适合您的观察者。

因此,事不宜迟,让我们创建一个新的 

watcher 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 配置 - 然后,如果望远镜正在记录,我们添加一种方法来记录查询。

最后,我们返回客户端及其配置。

那么我们如何记录我们的 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 Client 的导航项,

如果您打开它,您将看到日志出现在这里 - 您可以检查请求的标头、有效负载和状态。

因此,如果您开始看到 API 集成失败,这将极大地帮助您进行调试。

你觉得这有用吗?

您还使用哪些其他方式来监控和记录您的外部 API 请求?在推特上告诉我们!


转:

https://laravel-news.com/logging-external-http-requests-with-laravel-telescope

相关文章