Laravel怎么开启性能分析工具 _ Laravel Telescope安装方法【技巧】

1次阅读

telescope需laravel 8.0+和php≥8.0,安装前确认版本;执行composer require、telescope:install、migrate;确保app_debug=true、telescope_enabled=true、中间件放行、对应watcher启用并调优参数。

Laravel怎么开启性能分析工具 _ Laravel Telescope安装方法【技巧】

Telescope 装不上?先确认 Laravel 版本和 Composer 环境

Telescope 只支持 Laravel 8.0+,且要求 PHP ≥ 8.0。低于这个版本硬装会报 class "LaravelTelescopeTelescopeServiceProvider" not found 错误。

常见卡点是本地开发环境用的是 Laravel 7 或 Homestead 里 PHP 版本没切对。运行 php -vphp artisan --version 必须双双达标。

  • 运行 composer require laravel/telescope --dev(生产环境不建议启用)
  • 如果提示 Root composer.json requires laravel/telescope ^4.17 -> found laravel/telescope[v4.17.0] but the package is fixed to v4.16.0,说明有旧锁文件残留,删掉 vendor/composer.lock 再重装
  • 安装后别急着 php artisan telescope:install —— 先检查 config/app.php 是否已自动注册 LaravelTelescopeTelescopeServiceProvider::class,没注册就手动加进去(通常在 AppServiceProvider 之后)

执行 telescope:install 后访问 /telescope 404?检查路由注册和 APP_DEBUG

Telescope 默认只在 APP_DEBUG=true 时启用路由。如果 .env 里是 APP_DEBUG=false,即使装好了也完全看不到界面,连 404 都不报,直接 404。

另一个高频问题是:运行了 php artisan telescope:install,但没跑 php artisan migrate。Telescope 的数据表不会自动迁移,漏这步会导致页面空白或 JS 报 500 Error on /telescope/entries

  • 确保 .envAPP_DEBUG=true(线上绝对不要开)
  • 执行 php artisan migrate(不是 telescope:publish-migrations,后者只生成迁移文件,不执行)
  • 如果用了 Laravel Sail 或 docker,确认命令是在容器内执行的,宿主机跑 artisan 不生效
  • 某些 nginx 配置会拦截带下划线的路径,检查是否把 /telescope 当成非法路径给 403 了

能打开界面但没数据?看 TELESCOPE_ENABLED 和中间件配置

默认 Telescope 是“开着但不记录”的状态。关键开关在 config/telescope.phpenabled 项,它默认读环境变量 TELESCOPE_ENABLED。如果这个变量没设,值就是 NULL,等价于 false

另外,Telescope 默认只对本地请求记录(path 中间件限制),如果你用手机调试、postman 或跨域调用,得手动放开:

  • .env 加一行 TELESCOPE_ENABLED=true
  • 编辑 config/telescope.php,找到 middleware 数组,把 TelescopeMiddleware::class 换成 Authorize::class(或自定义中间件放行 IP)
  • 若只想记录 API 请求,把 watchers 里的 RequestWatcherignore_paths 删掉或调整,否则 /api/* 可能被默认过滤
  • 执行 php artisan telescope:clear 清下缓存再试,有时候旧配置卡在 config cache 里

想查慢查询或 redis 命令?确认对应 Watcher 已启用且参数合理

Telescope 默认只开 RequestWatcherLogWatcherQueryWatcherRedisWatcher 是关着的。开了也不代表全量捕获 —— 比如 QueryWatcher 默认只记录 > 100ms 的 sqlRedisWatcher 默认只记命令不记返回值。

性能分析真要起效,得动配置:

  • config/telescope.phpwatchers 数组里,把 QueryWatcher::classRedisWatcher::classenabled 设为 true
  • 调低 QueryWatcherslow 阈值,比如改成 'slow' => 50(单位毫秒)
  • RedisWatcher 加上 'with_values' => true 才能看到 GET user:123 返回了什么
  • 注意 CacheWatcher 会显著拖慢响应,仅调试时开启,上线前务必关掉

真正卡顿的地方往往不在 SQL,而在 N+1 查询或重复渲染 —— Telescope 的 ModelWatcherViewWatcher 才是定位这类问题的关键,但它们默认也是关闭的。

text=ZqhQzanResources