本地开发调试解决方案:Laravel Telescope


简介

Laravel Telescope 是一个专门为 Laravel 框架打造的优雅的调试助手。Telescope 可以为进入应用的请求、异常、日志、数据库查询、队列任务、邮件、通知、缓存操作、调度任务、变量打印等所有操作提供洞察明细功能,因此,它将成为你本地 Laravel 开发环境的又一绝佳伴侣。

安装

注:Telescope 要求 Laravel 5.7.7+ 版本。你可以通过 php artisan --version 查看自己的 Laravel 版本。

你可以使用 Composer 来安装 Telescope 到 Laravel 项目:

composer require laravel/telescope

安装完成后,使用 Artisan 命令 telescope:install 发布其公共资源,然后运行 migrate 命令执行数据库变更:

php artisan telescope:install
php artisan migrate

更新 Telescope

更新 Telescope 的时候,需要重新发布公共资源:

php artisan telescope:publish

只在指定环境安装

如果你计划只在本地开发环境安装 Telescope,可以在安装的时候使用 --dev 标记:

composer require laravel/telescope --dev

安装完成后,需要从 app 配置文件中移除 TelescopeServiceProvider 服务提供者的注册。取而代之地,要手动在 AppServiceProviderregister 方法中注册它:

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    if ($this->app->isLocal()) {
        $this->app->register(TelescopeServiceProvider::class);
    }
}

配置

发布完 Telescope 的公共资源后,它的配置文件位于 config/telescope.php。该配置文件允许你配置监听选项 watchers,每个配置项都包含其用途说明,所以建议你使用 Telescope 之前通篇读一下这个配置文件。

如果需要,你可以完全禁止 Telescope 的数据收集功能,通过配置项 enabled 来设置即可:

'enabled' => env('TELESCOPE_ENABLED', true),

数据清理

如果没有清理的话,telescope_entries 表会迅速累积记录。要缓解这一现状,需要通过调度任务每天运行 Artisan 命令 telescope:prune 来清理老数据:

$schedule->command('telescope:prune')->daily();

默认情况下,所有 24 小时之前的数据都会被清理,你可以在运行上述命令的时候使用 hours 选项来决定要保存多长时间以内的 Telescope 数据。例如,下面这个命令将会删除所有 48 小时以前创建的数据:

$schedule->command('telescope:prune --hours=48')->daily();

后台授权

Telescope 可以通过 /telescope 后台访问。和 Horizon 一样,默认情况下,你只能在本地开发环境(local)下访问。在你的 app/Providers/TelescopeServiceProvider.php 文件中,有一个 gate 方法,通过该访问控制方法,可以配置哪些用户可以在非本地环境访问 Telescope 后台,你可以根据需要随时修改该方法,以便限制对 Telescope 的访问:

/**
 * Register the Telescope gate.
 *
 * This gate determines who can access Telescope in non-local environments.
 *
 * @return void
 */
protected function gate()
{
    Gate::define('viewTelescope', function ($user) {
        return in_array($user->email, [
            'taylor@laravel.com',
        ]);
    });
}

点赞 取消点赞 收藏 取消收藏

<< 上一篇: 第三方登录解决方案:Laravel Socialite

>> 下一篇: 没有下一篇了