DylanBaine.com / Browse / Laravel Scheduler: how to send command output to STDOUT.

Laravel Scheduler: how to send command output to STDOUT.

If you rely on stdout for your Laravel logging for services like Data Dog or New Relic, you’ve likely ran into an issue where you can’t see the output of your Laravel commands that are called by the scheduler. In this post you’ll find that there is an easy solution to this issue.

Before I show you the solution, let me describe the issue. In a bare Laravel app, when the schedule runs, all that is logged to STDOUT is this:

  2023-03-22 13:34:03 Running ['artisan' inspire] ......................................................................... 452ms DONE
  ⇂ '/usr/bin/php8.2' 'artisan' inspire > '/dev/null' 2>&1  

As you will notice, we can see that the inspire command was run, but we can’t see the output of it. This isn’t helpful in the situation where the command throws an error, or you want to see important output of that command–in this case, an inspiring quote to whoever is digging through logs.

To solve this, I added the method below in my app/Console/Kernel.php file:

protected function scheduleWithOutput(Schedule $schedule, $command, array $parameters = []): Event
{
    $logFileName = Str::slug($command);
    $logFilePath = storage_path("logs/$logFileName.log");
    return $schedule->command($command, $parameters)
        ->sendOutputTo($logFilePath)
        ->then(function () use ($logFilePath) {
            echo "Command Output:" . file_get_contents($logFilePath);
        });
}

Then, in my schedule method, I schedule all of my jobs like this:

protected function schedule(Schedule $schedule): void
{
    $this->scheduleWithOutput($schedule, 'inspire')->everyMinute();
}

Now whenever the schedule runs, it puts the output of the command into a file that is unique for that job, and after the command runs, it echos out the contents of the file that the output was sent to.

  2023-03-22 13:36:15 Running ['artisan' inspire] Command Output:
  “ If you do not have a consistent goal in life, you can not live it in a consistent way. ”
  — Marcus Aurelius

......................................................................... 404ms DONE
  ⇂ '/usr/bin/php8.2' 'artisan' inspire > 'storage/logs/inspire.log' 2>&1  

I hope this was helpful to you! Happy coding 🙂