Skip to content

Commit

Permalink
[11.x] Add --json flag to queue:work command for structured loggi…
Browse files Browse the repository at this point in the history
…ng (#52887)

* feat(worker): Adds json sopport to queue:work command

* feat: duration job time in seconds to be friendly with tools like Grafana

* feat: add 'level' key with: 'info' or 'warning'

* chore: Reorganization of initial log

* lint

* lint

* formatting

---------

Co-authored-by: Jose Rodriguez <[email protected]>
Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
3 people authored Oct 8, 2024
1 parent b273941 commit 2599bc4
Showing 1 changed file with 60 additions and 4 deletions.
64 changes: 60 additions & 4 deletions src/Illuminate/Queue/Console/WorkCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Illuminate\Support\InteractsWithTime;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Terminal;
use Throwable;

use function Termwind\terminal;

Expand Down Expand Up @@ -44,7 +45,8 @@ class WorkCommand extends Command
{--sleep=3 : Number of seconds to sleep when no job is available}
{--rest=0 : Number of seconds to rest between jobs}
{--timeout=60 : The number of seconds a child process can run}
{--tries=1 : Number of times to attempt a job before logging it failed}';
{--tries=1 : Number of times to attempt a job before logging it failed}
{--json : Output the queue worker information as JSON}';

/**
* The console command description.
Expand Down Expand Up @@ -113,7 +115,7 @@ public function handle()
// connection being run for the queue operation currently being executed.
$queue = $this->getQueue($connection);

if (Terminal::hasSttyAvailable()) {
if (! $this->option('json') && Terminal::hasSttyAvailable()) {
$this->components->info(
sprintf('Processing jobs from the [%s] %s.', $queue, str('queue')->plural(explode(',', $queue)))
);
Expand Down Expand Up @@ -183,20 +185,35 @@ protected function listenForEvents()
});

$this->laravel['events']->listen(JobFailed::class, function ($event) {
$this->writeOutput($event->job, 'failed');
$this->writeOutput($event->job, 'failed', $event->exception);

$this->logFailedJob($event);
});
}

/**
* Write the status output for the queue worker for JSON or TTY.
*
* @param Job $job
* @param string $status
* @param Throwable|null $exception
* @return void
*/
protected function writeOutput(Job $job, $status, Throwable $exception = null)
{
$this->option('json')
? $this->writeOutputAsJson($job, $status, $exception)
: $this->writeOutputForCli($job, $status);
}

/**
* Write the status output for the queue worker.
*
* @param \Illuminate\Contracts\Queue\Job $job
* @param string $status
* @return void
*/
protected function writeOutput(Job $job, $status)
protected function writeOutputForCli(Job $job, $status)
{
$this->output->write(sprintf(
' <fg=gray>%s</> %s%s',
Expand Down Expand Up @@ -235,6 +252,45 @@ protected function writeOutput(Job $job, $status)
});
}

/**
* Write the status output for the queue worker in JSON format.
*
* @param \Illuminate\Contracts\Queue\Job $job
* @param string $status
* @param Throwable|null $exception
* @return void
*/
protected function writeOutputAsJson(Job $job, $status, Throwable $exception = null)
{
$log = array_filter([
'level' => $status === 'starting' || $status === 'success' ? 'info' : 'warning',
'id' => $job->getJobId(),
'uuid' => $job->uuid(),
'connection' => $job->getConnectionName(),
'queue' => $job->getQueue(),
'job' => $job->resolveName(),
'status' => $status,
'result' => match (true) {
$job->isDeleted() => 'deleted',
$job->isReleased() => 'released',
$job->hasFailed() => 'failed',
default => '',
},
'attempts' => $job->attempts(),
'exception' => $exception ? $exception::class : '',
'message' => $exception?->getMessage(),
'timestamp' => $this->now()->format('Y-m-d\TH:i:s.uP'),
]);

if ($status === 'starting') {
$this->latestStartedAt = microtime(true);
} else {
$log['duration'] = round(microtime(true) - $this->latestStartedAt, 6);
}

$this->output->writeln(json_encode($log));
}

/**
* Get the current date / time.
*
Expand Down

0 comments on commit 2599bc4

Please sign in to comment.