Cara Debug Aplikasi Laravel dengan Telescope
Cara debug aplikasi Laravel dengan Telescope adalah skill penting yang wajib dikuasai setiap developer Laravel. Saat aplikasi semakin kompleks, melacak bug dari log file atau dd() saja tidak cukup. Laravel Telescope hadir sebagai debugging assistant yang memberikan visibilitas penuh terhadap request, query database, job, notification, hingga exception secara real-time.
Dalam artikel ini, kita akan membahas cara install, konfigurasi, dan memanfaatkan fitur-fitur Telescope secara maksimal untuk proses debugging yang lebih cepat dan efisien.
Apa Itu Laravel Telescope?
Laravel Telescope adalah package resmi dari Laravel yang berfungsi sebagai debugging dashboard. Telescope merekam semua aktivitas yang terjadi di aplikasi, mulai dari HTTP request yang masuk, query SQL yang dijalankan, hingga job yang diproses di background.
Berbeda dengan tools logging biasa, Telescope menyediakan UI web yang interaktif sehingga kita bisa menelusuri setiap detail tanpa harus membuka terminal atau file log secara manual.
Fitur Utama Telescope
- Request Watcher: merekam semua incoming HTTP request beserta header, payload, dan response
- Query Watcher: menampilkan semua query SQL termasuk durasi eksekusi
- Exception Watcher: menangkap semua exception beserta stack trace lengkap
- Job Watcher: memantau status queue job (pending, completed, failed)
- Mail Watcher: preview email yang dikirim tanpa perlu cek mailbox
- Log Watcher: menampilkan log entry secara real-time
- Schedule Watcher: memantau eksekusi scheduled command
Instalasi Laravel Telescope
Pertama, install Telescope via Composer. Disarankan hanya di environment development:
composer require laravel/telescope --dev
Setelah package terinstall, jalankan perintah instalasi:
php artisan telescope:install
php artisan migrate
Perintah di atas akan membuat file konfigurasi config/telescope.php, service provider TelescopeServiceProvider, serta tabel migration yang diperlukan Telescope untuk menyimpan data.
Konfigurasi untuk Development Only
Agar Telescope tidak aktif di production, pastikan registrasi service provider hanya di environment tertentu. Buka file app/Providers/TelescopeServiceProvider.php:
public function register(): void
{
if ($this->app->environment('local')) {
$this->app->register(\Laravel\Telescope\TelescopeServiceProvider::class);
$this->app->register(TelescopeServiceProvider::class);
}
}
Tambahkan juga di .env:
TELESCOPE_ENABLED=true
Di production, set TELESCOPE_ENABLED=false agar tidak ada overhead performa.
Menggunakan Request Watcher untuk Debug API
Salah satu fitur paling sering dipakai adalah Request Watcher. Fitur ini merekam setiap HTTP request yang masuk beserta detail lengkapnya.
Akses Telescope di browser melalui URL /telescope. Di tab Requests, kamu bisa melihat:
- Method dan URL yang dipanggil
- Request headers dan body payload
- Response status code dan body
- Durasi total request
- User yang sedang login (jika ada)
Contoh Kasus: Debug API Response Tidak Sesuai
Misalnya ada endpoint API yang mengembalikan data tidak sesuai harapan. Daripada menambahkan dd() di controller, cukup buka Telescope dan cari request tersebut:
// app/Http/Controllers/OrderController.php
public function show(Order $order)
{
$order->load(['items.product', 'customer', 'payments']);
return new OrderResource($order);
}
Di Telescope, klik request /api/orders/123 dan periksa tab Response. Kamu langsung bisa lihat JSON response yang dikembalikan, tanpa perlu modifikasi kode sama sekali.
Debug Slow Query dengan Query Watcher
Query Watcher adalah senjata utama untuk menemukan query lambat. Telescope merekam semua query SQL beserta waktu eksekusi dalam milidetik.
Mengaktifkan Slow Query Threshold
Di file config/telescope.php, atur threshold untuk menandai query lambat:
'watchers' => [
Watchers\QueryWatcher::class => [
'enabled' => env('TELESCOPE_QUERY_WATCHER', true),
'slow' => 100, // query di atas 100ms ditandai sebagai slow
],
],
Setelah konfigurasi ini aktif, buka tab Queries di Telescope. Query yang melebihi threshold akan ditandai dengan label merah sehingga mudah diidentifikasi.
Contoh: Menemukan N+1 Query Problem
N+1 query adalah masalah klasik yang sering luput dari perhatian. Dengan Telescope, kamu bisa langsung melihat jumlah query per request:
// Tanpa eager loading - menghasilkan N+1 query
$orders = Order::all();
foreach ($orders as $order) {
echo $order->customer->name; // query baru setiap iterasi
}
// Dengan eager loading - hanya 2 query
$orders = Order::with('customer')->get();
foreach ($orders as $order) {
echo $order->customer->name;
}
Di Telescope, request pertama akan menampilkan puluhan query, sedangkan request kedua hanya 2 query. Perbedaannya langsung terlihat jelas.
Tracking Exception dan Error
Exception Watcher menangkap semua exception yang terjadi, baik yang di-handle maupun tidak. Setiap entry menampilkan:
- Class exception (misalnya
ModelNotFoundException) - Pesan error
- Stack trace lengkap
- Request yang memicu exception
- File dan line number
Filter Exception yang Tidak Perlu Direkam
Beberapa exception seperti AuthenticationException atau ValidationException mungkin tidak perlu direkam karena merupakan flow normal. Tambahkan filter di TelescopeServiceProvider:
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
public function register(): void
{
Telescope::filter(function (IncomingEntry $entry) {
if ($entry->type === 'exception') {
// Abaikan validation exception
return !$entry->content['class'] === 'Illuminate\\Validation\\ValidationException';
}
return true;
});
}
Monitoring Queue Job dengan Job Watcher
Untuk aplikasi yang menggunakan queue, Job Watcher sangat membantu. Setiap job yang diproses akan tercatat beserta:
- Nama job class
- Payload data
- Status (processed, failed, pending)
- Queue connection dan queue name
- Durasi eksekusi
- Exception jika gagal
Debug Failed Job
Ketika sebuah job gagal, klik entry di tab Jobs untuk melihat detail error:
// app/Jobs/ProcessInvoice.php
class ProcessInvoice implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public Order $order
) {}
public function handle(): void
{
// Generate PDF invoice
$pdf = PDF::loadView('invoices.template', [
'order' => $this->order->load('items'),
]);
Storage::put("invoices/{$this->order->id}.pdf", $pdf->output());
// Kirim email ke customer
Mail::to($this->order->customer->email)
->send(new InvoiceMail($this->order));
}
}
Jika job ini gagal karena relasi customer null, Telescope akan menampilkan Trying to access property on null beserta stack trace yang menunjuk ke baris $this->order->customer->email. Kamu bisa langsung tahu akar masalahnya.
Tips Optimasi Penggunaan Telescope
Batasi Data yang Direkam
Telescope menyimpan data ke database, sehingga bisa membengkak jika tidak dibatasi. Jadwalkan pruning secara otomatis:
// app/Console/Kernel.php
protected function schedule(Schedule $schedule): void
{
$schedule->command('telescope:prune --hours=48')->daily();
}
Perintah ini akan menghapus data Telescope yang lebih dari 48 jam setiap hari.
Nonaktifkan Watcher yang Tidak Diperlukan
Jika hanya butuh debug query, matikan watcher lain untuk mengurangi overhead:
// config/telescope.php
'watchers' => [
Watchers\CacheWatcher::class => false,
Watchers\DumpWatcher::class => false,
Watchers\EventWatcher::class => false,
Watchers\GateWatcher::class => false,
Watchers\MailWatcher::class => true,
Watchers\ModelWatcher::class => false,
Watchers\NotificationWatcher::class => false,
Watchers\QueryWatcher::class => true, // aktifkan ini saja
Watchers\RequestWatcher::class => true,
Watchers\ScheduleWatcher::class => false,
],
Gunakan Telescope di Staging Server
Selain local development, Telescope juga berguna di staging server untuk debug masalah yang sulit direproduksi di local. Pastikan akses dibatasi dengan authorization gate:
// app/Providers/TelescopeServiceProvider.php
protected function gate(): void
{
Gate::define('viewTelescope', function ($user) {
return in_array($user->email, [
'zaki@example.com',
'admin@example.com',
]);
});
}
Hanya user dengan email yang terdaftar yang bisa mengakses dashboard Telescope di staging.
Alternatif dan Pelengkap Telescope
Telescope sangat powerful untuk debugging di development, tapi ada beberapa tools pelengkap yang bisa dikombinasikan:
- Laravel Debugbar: menampilkan debug info langsung di browser sebagai toolbar
- Clockwork: alternatif profiling dengan Chrome DevTools integration
- Sentry: untuk error tracking di production (Telescope tidak disarankan di production)
Kombinasi Telescope di development dan Sentry di production adalah setup yang umum digunakan di banyak tim.
Kesimpulan
Laravel Telescope adalah tools debugging yang sangat berguna untuk mempercepat proses development. Dengan memanfaatkan fitur Request Watcher, Query Watcher, Exception Watcher, dan Job Watcher, kamu bisa menemukan bug lebih cepat tanpa perlu menambahkan dd() atau Log::info() di mana-mana.
Langkah-langkah penting yang perlu diingat:
- Install Telescope hanya di development (
--dev) - Konfigurasi threshold slow query sesuai kebutuhan
- Filter exception yang tidak relevan agar dashboard tetap bersih
- Jadwalkan pruning agar database tidak membengkak
- Batasi akses dengan authorization gate jika digunakan di staging
Dengan Telescope, proses debugging jadi lebih visual, terstruktur, dan efisien. Selamat mencoba!