Setting Up Logging and Error Tracking with Sentry in Laravel




Error tracking and logging are crucial for maintaining the health and performance of any application. Sentry is a popular open-source error tracking tool that helps developers identify and resolve errors in real time. This article will guide you through the process of setting up Sentry for logging and error tracking in a Laravel application.


What is Sentry?


Sentry is an error monitoring tool that helps you monitor and fix crashes in real time. It provides rich context about the errors, including stack traces, user actions, and more, which helps developers quickly identify and resolve issues.


Why Use Sentry?


Real-Time Error Tracking: Get notified of errors as they happen.

Detailed Reports: Access comprehensive error reports with stack traces, breadcrumbs, and context.

User Context: Understand how errors affect specific users.

Integration: Integrate with various platforms and frameworks, including Laravel.


Setting Up Sentry in a Laravel Application


Follow these steps to set up Sentry for logging and error tracking in your Laravel application.


Step 1: Install Sentry SDK


Use Composer to install the Sentry Laravel SDK:


composer require sentry/sentry-laravel


Step 2: Publish the Sentry Configuration


Publish the Sentry configuration file using the following Artisan command:


php artisan vendor:publish --tag=sentry-config


This will create a `sentry.php` configuration file in the `config` directory.


Step 3: Configure Sentry


Open the `config/sentry.php` file and configure it with your Sentry DSN (Data Source Name). You can find your DSN in your Sentry project settings.


return [

    'dsn' => env('SENTRY_LARAVEL_DSN'),


    // Capture bindings on SQL queries logged in breadcrumbs

    'breadcrumbs.sql_bindings' => true,


    // Capture default Integrations

    'default_integrations' => true,


    // Capture SQL queries in breadcrumbs

    'breadcrumbs.sql_queries' => true,


    // Capture SQL query parameter in breadcrumbs

    'breadcrumbs.sql_query_bindings' => true,


    // Customize error levels for log channels

    'error_levels' => [

        'log' => 'warning', // change 'log' to your desired log level

    ],

];


Next, add the Sentry DSN to your `.env` file:


SENTRY_LARAVEL_DSN=https://your-dsn@sentry.io/project-id


Step 4: Integrate Sentry with Laravel


Laravel provides built-in support for error logging. To use Sentry as your logging provider, update the `report` method in the `app/Exceptions/Handler.php` file.


// Handler.php

use Sentry\State\HubInterface;

use Throwable;


public function report(Throwable $exception)

{

    if (app()->bound(HubInterface::class) && $this->shouldReport($exception)) {

        app(HubInterface::class)->captureException($exception);

    }


    parent::report($exception);

}


This ensures that all exceptions are reported to Sentry.


Step 5: Verify Sentry Integration


To verify that Sentry is correctly configured, you can manually trigger an error and check if it appears in your Sentry dashboard.


Add a route to trigger an error:


// web.php

Route::get('/debug-sentry', function () {

    throw new Exception('My first Sentry error!');

});


Access this route in your browser (`http://your-app-url/debug-sentry`) and check your Sentry dashboard for the error.


Advanced Sentry Configuration


User Context


You can send user information to Sentry, which helps in tracking errors related to specific users.


use Sentry\State\Scope;


Sentry\configureScope(function (Scope $scope): void {

    $scope->setUser([

        'id' => Auth::id(),

        'email' => Auth::user()->email,

    ]);

});


Breadcrumbs


Breadcrumbs are a trail of events that lead up to an error. Sentry automatically captures breadcrumbs for HTTP requests, database queries, and more. You can manually add breadcrumbs as well:


Sentry\addBreadcrumb(new Breadcrumb(

    Breadcrumb::LEVEL_INFO,

    Breadcrumb::TYPE_DEFAULT,

    'custom',

    'Custom breadcrumb message'

));


Custom Tags and Extra Data


Adding custom tags and extra data can provide additional context for your errors.


Sentry\configureScope(function (Scope $scope): void {

    $scope->setTag('page_locale', 'en-us');

    $scope->setExtra('character_name', 'Mighty Fighter');

});


Release Tracking


Sentry allows you to track releases and associate errors with specific releases. Set the release version in your configuration:


'sentry' => [

    'dsn' => env('SENTRY_LARAVEL_DSN'),

    'release' => env('SENTRY_RELEASE'),

],


Add the release version to your `.env` file:


SENTRY_RELEASE=your-app-version



Setting up Sentry for logging and error tracking in your Laravel application enhances your ability to detect, diagnose, and resolve issues promptly. By following the steps outlined in this guide, you can integrate Sentry seamlessly into your Laravel project, ensuring real-time error monitoring and comprehensive insights into your application's health. This setup not only improves your development workflow but also contributes to a more robust and reliable application for your users.