Laravel 用 Telescope 做开发期调试:请求、查询、异常与队列一目了然
test12026-10-190 次阅读
本地调试靠 dump 太慢
排查慢接口时,光看代码很难发现是哪条 SQL 没走索引、哪个队列任务悄悄失败。Telescope 是 Laravel 官方调试面板,把最近的请求、命令、队列、异常、模型变更全部记录下来,点开就能看到完整上下文。
安装与路由守卫
开发环境用 composer 装,发布配置后把入口限制在内网或本地,避免生产环境暴露。
composer require laravel/telescope --dev
php artisan telescope:install
php artisan migrate
在 TelescopeServiceProvider 里只允许本地访问:
protected function gate()
{
Gate::define('viewTelescope', function ($user = null) {
return app()->environment('local');
});
}
查看慢查询与 N+1
进 Telescope 的 Queries 页,按耗时排序能直接看到超过阈值的语句;配合 laravel-debugbar 或单独开启查询计数,能快速定位循环里漏写 with 导致的 N+1。
// 错误示范:循环里每条都查一次作者
foreach ($posts as $post) {
echo $post->author->name;
}
// 正确:预加载,Telescope 里查询数从 N+1 降到 2
$posts = Post::with('author')->get();
捕获异常与队列失败
Exceptions 页记录每次未捕获异常、请求入参与堆栈;Queues 页能看到任务 payload、attempts 和被放入 failed_jobs 的原因,比翻日志快得多。
// 让队列失败可追踪:失败任务自动进 failed_jobs 表
dispatch(new SendReceipt($order));
// 在 Telescope Queues 里能看到每条的 status、exception
落地要点
- Telescope 只在 local/testing 启用,生产环境装了也要用 gate 关掉查看入口。
- 记录量大时定期清 telescope_entries 表,或配置只保留最近几天。
- 它自己也会产生数据库写入,压测前记得临时关闭,避免干扰指标。
- 敏感字段(密码、令牌)用 Telescope 的 redact 配置做脱敏,别把密钥记进表。
T
test1
文章作者
本地调试靠 dump 太慢 排查慢接口时,光看代码很难发现是哪条 SQL 没走索引、哪个队列任务悄悄失败。Telesc...
- 分类
- 技术
- 发布时间
- 2026-10-19
- 字数
- 约 1114 字
- 阅读
- 0 次
