LoginSignup
0
0

More than 3 years have passed since last update.

How to adopt Sentry to Laravel 6 with user context

Posted at

Check your Laravel version before get started.

$ php artisan --version

Installation Sentry

$ composer require sentry/sentry-laravel:1.8.0

Adding sentry DSN on your env

.env
SENTRY_LARAVEL_DSN=https://[YOUR_URL]        

Make config file for Sentry

$ touch config/sentry.php
config/sentry.php
<?php
return array(
    'dsn' => env('SENTRY_LARAVEL_DSN'),
    'breadcrumbs.sql_bindings' => true,
    'send_default_pii' => true
);

Modify your Hander file

app/Exceptions/Handler.php
     public function report(Exception $exception)
     {
+        if (app()->bound('sentry') && $this->shouldReport($exception)) {
+            app('sentry')->captureException($exception);
+        }
+
         parent::report($exception);
     }

Adding user context

$ php artisan make:middleware SentryContext
app/Http/Middleware/SentryContext.php
<?php
namespace App\Http\Middleware;

use Closure;
use Sentry\State\Scope;

class SentryContext
{
    /** 
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {   
        if (auth()->check() && app()->bound('sentry')) {
            \Sentry\configureScope(function (Scope $scope): void {
                $scope->setUser([
                    'id' => auth()->user()->id,
                    // since email is sensitive information, be careful to handle it.
                    //'email' => auth()->user()->email,
                ]); 
            }); 
        }   

        return $next($request);
    } 
}
app/Http/Kernel.php
    protected $routeMiddleware = [ 
        ...
+       'sentry.context' => \App\Http\Middleware\SentryContext::class
    ];  

Adding group on route

route/web.php
Route::middleware(['sentry.context'])->group(function () {
    Route::get('/', 'ToppageController@index')->name('home');
    // or page as you like
}); 

Artboard.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0