Logging Laravel background tasks in Heroku the right way

(Guest post by Itai Koren)

Problem

I have been using Cron To Go for quite some time now to schedule Laravel tasks. However, I noticed that when a job fails, even though I get notifications from Cron To Go, the application log I use to debug failed tasks is simply empty.

This works great, but where are my logs?

So what went wrong?

I realized that the underlying issue is that Laravel pipes all outputs to /dev/null, meaning that nothing is emitted, while Heroku’s Logplex is aggregating logs from running processes’ stdout and stderr. Therefore, I am only left with a few lines that show that the process started and then exited with a failure, and nothing more.

Solution

I set out to address this issue and found that it can be solved with a slight change in the job command, without any code or configuration changes, maintaining consistency over all platforms.

By default, Laravel logs everything to a single channel as defined in logging.php. The logs go to the file /storage/logs/laravel.log. So, instead of forcing Laravel to log to stdout or stderr, we’ll just emit the log from this file to stdout. To do this, simply replace  the job command in Cron to Go from php artisan schedule:run with:

touch ./storage/logs/laravel.log; tail -f ./storage/logs/laravel.log & php artisan schedule:run
Sweet! Laravel jobs run properly and logs are visible!

Breaking the command to its 3 parts:

  1. touch .storage/logs/laravel.log - this part makes sure that the output command exists
  2. tail -f ./storage/logs/laravel.log - use tail to continuously emit what’s written to the file, to stdout.
  3. php artisan schedule:run - and run the scheduler.

Advantages

Thanks to Cron To Go’s notifications and the newly established logs, I am better prepared to fix problems quickly in any instance that a task were to fail.


About Itai Koren

I’ve been building cool ecommerce solutions since 2017. I like complicated problems with elegant solutions. I'm a critical thinker and awful story teller (although my 2-year-old daughter would disagree).

Run and Monitor Scheduled Tasks on your Favorite Apps
Cron To Go simplifies the monitoring, alerting, and management of your cron jobs' performance, uptime, and status - ensuring seamless operation.
Try Cron To Go for free!