Skip to content

Instantly share code, notes, and snippets.

@macedd
Created November 6, 2019 22:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macedd/f893e8095580d983ec309653667bcddb to your computer and use it in GitHub Desktop.
Save macedd/f893e8095580d983ec309653667bcddb to your computer and use it in GitHub Desktop.
Laravel Queue Instrumentation Trait
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Log;
use \App\Traits\QueueInstrumentationTrait;
abstract class Job implements ShouldQueue
{
use QueueInstrumentationTrait;
use InteractsWithQueue, Queueable, SerializesModels;
}
<?php
namespace App\Traits;
use Log;
trait QueueInstrumentationTrait
{
/**
* Instruments calls to queue's job handle.
*
* @return void
*/
public function handle()
{
$payload = [];
$start = microtime(true);
try {
// call the actual job handle method
app()->call([$this, 'parent::' . __FUNCTION__]);
} catch (\Exception $e) {
// collect errors
$payload = array_merge($payload, [
'job_params' => get_object_vars($this),
'job_error' => exception_array($e, false),
]);
throw $e;
} finally {
// time spent processing
$time = microtime(true) - $start;
// job identification
$payload = array_merge($payload, [
'job_name' => get_called_class(),
'job_server' => gethostname(),
'server_time' => $time,
]);
// log out
Log::withName('InstrumentationTrait')->info(json_encode($payload));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment