How to Set up and Configure Telescope in Laravel
Posted on August 20th, 2024
Laravel Telescope is a powerful debugging tool designed for Laravel applications. It provides detailed insights into various aspects of your application, such as incoming requests, exceptions, database queries, queued jobs, emails, notifications, and more. Telescope enhances the developer experience by offering these insights, making debugging and monitoring applications easier during development.
Prerequisites
Before you begin setting up Laravel Telescope, make sure you have the following prerequisites:
- Composer: Ensure Composer is installed on your local machine. Composer is a dependency manager for PHP that you can download from getcomposer.org.
- Laravel Project: Set up and run a Laravel project. It’s recommended that you use Laravel version 5.7 or higher. You can create a new Laravel project by following the instructions on the Laravel installation page.
Installing Laravel Telescope
To add Telescope to your Laravel project, follow these steps:
Step 1 – Open your terminal or command prompt: This is where you will enter the commands to set up Telescope.
Step 2 – Navigate to your Laravel project directory:
cd /path/to/your/laravel/project
Replace /path/to/your/laravel/project
with the path to your Laravel project directory.
Step 3 – Install Laravel Telescope using the following command:
composer require laravel/telescope --dev
This command installs Telescope as a development dependency. The --dev
flag ensures that Telescope is only included in your development environment and not in production.
Publishing Telescope Assets
After installing Telescope, you need to publish its assets, including configuration files, migrations, and views. You can do it by executing the following command in your terminal.
php artisan telescope:install
This command copies essential files such as the configuration file (config/telescope.php
), and migrations into your Laravel project.
Running Telescope Migrations
Telescope requires a database table to store the monitoring data it collects. To set up these tables, run the following command to migrate:
php artisan migrate
This command creates the necessary tables (telescope_entries
, telescope_entries_tag
, telescope_monitoring
, etc.) in your configured database.
Configuring Telescope
You can customize the Telescope’s behaviour using the configuration file at config/telescope.php
. Here’s a breakdown of the settings:
Master Switch:
The Master Switch is a key configuration that enables or disables the Telescope module in your application. This is useful for toggling the monitoring functionality without altering the main codebase.
'enabled' => env('TELESCOPE_ENABLED', true),
Domain and Path:
This section specifies the domain and path where Telescope can be accessed. It’s beneficial for securing the monitoring dashboard by specifying a custom path and limiting access to certain domains.
'domain' => env('TELESCOPE_DOMAIN'), 'path' => env('TELESCOPE_PATH', 'telescope'),
Storage Driver:
The Storage Driver configuration sets how the Telescope data will be stored. By default, it uses the database driver, which is useful for retaining monitoring insights for future analysis.
'driver' => env('TELESCOPE_DRIVER', 'database'),
Queue Configuration:
This section outlines the settings for the Queue Configuration, allowing you to specify which connection and queue Telescope should use. This helps optimize performance by decoupling monitoring tasks from primary application processes.
'queue' => [ 'connection' => env('TELESCOPE_QUEUE_CONNECTION', null), 'queue' => env('TELESCOPE_QUEUE', null), ],
Route Middleware:
Route Middleware defines the middleware that will be applied to the Telescope routes. This is essential for ensuring that access to the Telescope interface is properly secured and managed through necessary checks.
'middleware' => [ 'web', Authorize::class, ],
Allowed/Ignored Paths and Commands:
This configuration specifies which paths and commands are either allowed or ignored by Telescope. This is useful to focus monitoring efforts on relevant areas while excluding those that do not require tracking.
'only_paths' => [], 'ignore_paths' => [ 'livewire*', 'nova-api*', 'pulse*', ], 'ignore_commands' => [],
Securing the Telescope Dashboard
You must configure dashboard authorization to ensure only authorized users can access the Telescope dashboard. By default, Telescope uses Laravel’s authentication system to restrict access.
Define Authorization Logic: Open the TelescopeServiceProvider located in app/Providers/TelescopeServiceProvider.php
and update the gate method:
protected function gate() { Gate::define('viewTelescope', function ($user) { return in_array($user->email, [ '[email protected]', ]); }); }
Replace '[email protected]'
with the email addresses of users who should have access to the Telescope dashboard.
Accessing Telescope Dashboard
After setting up and configuring Telescope, you can access the Telescope dashboard in your browser using the configured path. For example, if you kept the default path, you can access it at http://your-laravel-app.test/telescope. This dashboard provides a comprehensive view of all monitored aspects of your Laravel application.
Understanding Telescope Features
Telescope offers powerful features to help debug and monitor your Laravel application. Here’s a brief overview of each section:
- Requests: Logs every HTTP request to your application, including request method, URL, status code, duration, and time.
- Commands: This tracker tracks all Artisan commands executed within your application, including the command, arguments, options, and execution time.
- Schedule: Displays all scheduled tasks defined in your
App\Console\Kernel.php
file, including execution time, duration, and success/failure status. - Jobs: Provides insights into queued jobs in your application, including status, creation time, and processing time.
- Batches: Monitors Laravel’s batch processing, including job counts, statuses, and batch timings.
- Cache: Logs all cache operations, including hits, misses, and keys involved.
- Dumps: Shows all dump output captured during the request lifecycle.
- Events: Logs all events fired in your application, including event name, payload, and listeners.
- Exceptions: Tracks all exceptions thrown in your application, including message, stack trace, and time.
- Gates: Monitors authorization gates and policies, logging checks and results.
- HTTP Client: Logs all outgoing HTTP requests made by your application using Laravel’s HTTP client.
- Logs: Displays log entries recorded by your application, including levels, messages, and time.
- Mail: Logs all emails sent by your application, including recipient, subject, and delivery status.
- Models: Tracks Eloquent model changes, including create, update, and delete operations.
- Notifications: Logs all notifications sent by your application, including notifiable entity, notification type, and delivery status.
- Queries: Logs all database queries executed by your application, including SQL query, bindings, duration, and time.
- Redis: Tracks all Redis operations performed by your application, including commands, keys, and durations.
- Views: Logs all Blade views rendered by your application, including view name, data, and rendering time.
Data Pruning
Without pruning, the telescope_entries table can accumulate records quickly. To mitigate this, schedule the telescope:prune Artisan command to run daily:
$schedule->command('telescope:prune')->daily();
By default, all entries older than 24 hours will be pruned. You can adjust the retention period using the hours
option. For example, to delete all records older than 48 hours:
$schedule->command('telescope:prune --hours=48')->daily();
Advanced Usage Examples
Explore advanced use cases with Telescope to optimize and debug your Laravel application:
- Analyzing Database Queries: Identify slow queries and optimize database interactions based on Telescope insights.
- Debugging Exceptions: Utilize Telescope’s detailed exception logs to diagnose and fix runtime errors efficiently.
- Monitoring Queued Jobs: Track queued jobs to ensure they execute as expected and troubleshoot failed attempts.
Customizing Telescope
Customize Telescope to fit your specific debugging and monitoring needs:
- Modifying Configuration: Adjust
config/telescope.php
settings to change the dashboard path, enable/disable features, and configure storage options. - Adding Custom Watchers: Extend Telescope by adding custom watchers to monitor additional aspects of your application’s behavior.
- Integrating with Other Tools: Combine Telescope with Laravel Debugbar or Horizon for enhanced monitoring capabilities.
Best Practices for Using Telescope
Follow these best practices to maximize the effectiveness of Telescope:
- Regular Review: Periodically review Telescope logs to identify performance bottlenecks and resolve issues promptly.
- Optimization: Use Telescope insights to optimize application performance and enhance user experience.
- Security: Secure Telescope’s dashboard by configuring appropriate middleware and access controls.
Conclusion
The Laravel Telescope is an indispensable tool for Laravel developers. It offers comprehensive insights and debugging capabilities during application development. Following this guide, you can effectively set up, configure, and utilize Telescope to streamline debugging processes, optimize application performance, and ensure robust application operation.
Additional Resources
For further reading and resources on Laravel Telescope:
By understanding and using Laravel Telescope, you can significantly improve your development workflow, making it easier to identify and resolve issues, monitor application performance, and ensure a smoother development process.