I have Installed sentry and it enabled user_context in the configuration file. I've also added the context file to add user context data. Here's my user context code:
if (auth()->check()) {
$sentry->user_context([
'id' => auth()->user()->id,
'username' => auth()->user()->name,
'email' => auth()->user()->email
]);
} else {
$sentry->user_context(['id' => null]);
}
How do I go about linking up the sentry context middleware? Do I just add it to $middleware in kernel.php?
If you implemented the middleware like this:
https://github.com/getsentry/sentry-laravel#adding-context
You can add the middleware to the $middleware as long as your Illuminate\Session\Middleware\StartSession middleware is before it (otherwise the user/session is not loaded yet), so you might want to add it to the web middleware group.
If you are on 5.6 (maybe 5.5 not sure) you can also listen for the \Illuminate\Auth\Events\Authenticated event in your EventServiceProvider to know when Laravel has set the auth()->user() (this happens on every request not just login).
Example listener:
<?php
namespace App\Listeners\Auth;
use App\User;
use Illuminate\Auth\Events\Authenticated as Event;
class AuthenticatedEventListener
{
/**
* Handle the user authenticated event.
*
* @param \Illuminate\Auth\Events\Authenticated $event
*/
public function handle(Event $event): void
{
if ($event->user instanceof User) {
// Set the Sentry user context here
// No need to use `$sentry->user_context(['id' => null]);`
}
}
}
Please let me know if it helps.
Closing this issue because it is quite old, if there is still a problem please open a new issue.
Most helpful comment
If you implemented the middleware like this:
https://github.com/getsentry/sentry-laravel#adding-context
You can add the middleware to the
$middlewareas long as yourIlluminate\Session\Middleware\StartSessionmiddleware is before it (otherwise the user/session is not loaded yet), so you might want to add it to thewebmiddleware group.If you are on 5.6 (maybe 5.5 not sure) you can also listen for the
\Illuminate\Auth\Events\Authenticatedevent in yourEventServiceProviderto know when Laravel has set theauth()->user()(this happens on every request not just login).Example listener:
Please let me know if it helps.