Record the source of job dispatch

Viewed 44

I'm curious if you guys know any easy and reliable way to track the source of what dispatched a Laravel job.

My use case for this is that I often have to debug failing jobs and knowing why, where and how they were dispatched would be very useful, e.g. could add it as metadata to Sentry reports.

I mean adding a property to a job would probably do it, but I'm wondering if there's some way that would not involve code changes in individual jobs.

1 Answers

I think you're looking for Job Events (Laravel documentation)

You could add this to your app/Providers/AppServiceProvider.php - boot() method or you could create one QueueJobProvider for example and add your provider in config/app.php inside the 'providers' key.

With this events you can have the payload as you want and more proprities. You can learn more about this issue in Laravel docs here

use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\Events\JobExceptionOccurred;    

Queue::before(function (JobProcessing $event) {
    // \Log::info($event);
    // \Log::info($event->job->payload());
});

Queue::after(function (JobProcessed $event) {
    // \Log::info($event);
    // \Log::info($event->job->payload());
});

Queue::failing(function (JobFailed $event) {
    // \Log::info($event);
    // \Log::info($event->job->payload());
});

Queue::exceptionOccurred(function (JobExceptionOccurred $event) {
    // \Log::info($event);
    // \Log::info($event->job->payload());
});
Related