前言
當 Laravel 應用在生產環境出現效能問題,你第一個想到的工具是什麼?Log?dd()?還是靠感覺猜?有了 Laravel Telescope,你可以像有透視眼一樣,清楚看到每個請求的 SQL 查詢、Cache 命中、Queue 任務、Exception,甚至 Mail 發送內容。本文帶你從安裝到實戰使用,完整掌握 Telescope。
安裝 Telescope
composer require laravel/telescope --dev php artisan telescope:install php artisan migrate
注意:--dev 代表只在開發環境安裝。如果你需要在生產環境的特定帳號使用 Telescope,可以不加 --dev,但務必做好存取控制(見下方)。
設定 AppServiceProvider
安裝後,Telescope 預設在所有環境啟動。推薦在 AppServiceProvider 中限制只在特定環境載入:
// app/Providers/AppServiceProvider.php
use Laravel\Telescope\Telescope;
public function register(): void
{
// 只在 local 環境載入 Telescope
if ($this->app->environment('local')) {
$this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
$this->app->register(TelescopeServiceProvider::class);
}
}
存取控制
Telescope Dashboard 預設路徑是 /telescope。在生產環境必須設定 Gate 限制誰可以存取:
// app/Providers/TelescopeServiceProvider.php
protected function gate(): void
{
Gate::define('viewTelescope', function ($user) {
// 只允許特定 email 存取
return in_array($user->email, [
'[email protected]',
'[email protected]',
]);
// 或者用 role 判斷
// return $user->hasRole('developer');
});
}
Telescope Dashboard 各功能說明
Requests(請求監控)
每個 HTTP 請求的完整快照:URL、Method、Response Code、執行時間、記憶體用量,以及這個請求觸發的所有 SQL、Cache、Event。這是排查問題的起點。
| 欄位 | 用途 |
|---|---|
| Duration | 請求總耗時,超過 500ms 要警戒 |
| Queries | SQL 查詢次數,超過 20 條要排查 N+1 |
| Memory | 記憶體峰值,找記憶體洩漏的線索 |
Queries(SQL 查詢)
所有 SQL 查詢,含執行時間。Telescope 會標記慢查詢(預設超過 100ms),讓你一眼找到效能瓶頸:
// config/telescope.php
// 調整慢查詢閾值(毫秒)
'slow_query_threshold' => env('TELESCOPE_SLOW_QUERY_MS', 100),
實際上,你在 Telescope Queries 頁面會看到:
- 完整 SQL(含 binding 值,不是問號)
- 執行時間(ms)
- 觸發這條 SQL 的 PHP 呼叫堆疊(Connection → Model → Controller)
Models(Eloquent 監控)
記錄所有 Eloquent 操作(created / updated / deleted),讓你追蹤資料變動的來源。排查「這筆資料是誰改的?」時非常有用。
Cache(快取監控)
記錄每個 Cache Hit / Miss / Set / Forget,是優化快取策略的好幫手:
// 你可以在 Telescope 看到: // [HIT] user:42 (0.3ms) // [MISS] product:99 → 觸發 DB 查詢 // [SET] product:99 TTL: 3600s
Jobs(Queue 任務)
所有排入 Queue 的 Job,包含:
- Job 名稱、Queue 名稱、連線
- 執行狀態(pending / running / completed / failed)
- 執行時間與 attempt 次數
- 失敗時的 Exception 訊息與 stack trace
Exceptions(例外監控)
所有未被捕獲的例外,含完整 stack trace、發生的 URL、使用者資訊。比翻 log 檔快十倍。
Mail(郵件預覽)
可直接在 Telescope 預覽郵件 HTML 內容,不需要實際收到信,開發時非常方便:
// .env 設定讓 mail 不實際發送,只記錄到 Telescope MAIL_MAILER=log
客製化:只記錄你關心的資料
Telescope 預設記錄所有東西,在高流量站台可能佔用大量儲存空間。透過 filtering 精準控制:
// app/Providers/TelescopeServiceProvider.php
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
protected function gate(): void { /* ... */ }
public function register(): void
{
// 只記錄有問題的請求
Telescope::filter(function (IncomingEntry $entry) {
if ($this->app->environment('local')) {
return true; // local 記錄全部
}
// production 只記錄:
return $entry->isReportableException() // 有例外
|| $entry->isFailedRequest() // HTTP 4xx/5xx
|| $entry->isFailedJob() // 失敗的 Job
|| $entry->isScheduledTask() // 排程任務
|| $entry->hasMonitoredTag(); // 有監控 tag
});
}
手動標記重要請求
use Laravel\Telescope\Telescope;
// 在 Controller 或 Middleware 中標記
Telescope::tag(function (IncomingEntry $entry) {
// 標記慢請求
if ($entry->type === 'request' && $entry->content['duration'] > 1000) {
return ['slow-request'];
}
// 標記特定 API 版本
if (str_starts_with($entry->content['uri'] ?? '', '/api/v2')) {
return ['api-v2'];
}
return [];
});
清理舊資料
Telescope 資料存在 telescope_entries 資料表,長期累積會很大,建議設定自動清理:
// config/telescope.php
'prune_older_than' => 48, // 保留最近 48 小時的資料
// 手動清理
php artisan telescope:prune
// 排程自動清理(每天清一次)
// app/Console/Kernel.php
$schedule->command('telescope:prune')->daily();
// 或只保留 24 小時
$schedule->command('telescope:prune --hours=24')->daily();
實戰:用 Telescope 排查一個效能問題
以下是一個完整的排查流程示範:
# 情境:/api/orders 回應時間從 200ms 暴增到 3000ms # Step 1: 打開 Telescope → Requests # 找到 /api/orders,點進去 # Step 2: 查看 Queries 數量 # 發現這個請求執行了 142 條 SQL → N+1 問題確認 # Step 3: 點開 Queries 列表 # 發現重複執行: # SELECT * FROM `users` WHERE `id` = 1 (重複 100 次) # SELECT * FROM `users` WHERE `id` = 2 (重複 100 次) # ... # Step 4: 查看 SQL 的 call stack # 找到觸發的程式碼:OrderController@index → Order::all() → $order->user # Step 5: 修正
// 修正前(N+1)
$orders = Order::all();
foreach ($orders as $order) {
echo $order->user->name; // 每次都查一次 users
}
// 修正後(Eager Loading)
$orders = Order::with('user')->get();
foreach ($orders as $order) {
echo $order->user->name; // 已預載,無額外查詢
}
// 修正後:142 條 SQL → 2 條 SQL,回應時間回到 120ms ✅
小結
Laravel Telescope 是開發與除錯階段不可或缺的工具。它讓隱形的效能問題變得可視化:
- Requests:找慢請求的入口
- Queries:找 N+1 和慢 SQL
- Cache:評估快取策略效果
- Jobs:監控非同步任務狀態
- Exceptions:第一時間掌握錯誤
搭配前幾篇介紹的 N+1 修正、Redis 快取、MySQL Index 優化技巧,Telescope 就是你確認這些優化是否真正生效的最後防線。