How to save cron job output to a log file

By: Shane Harter|Last Updated: Dec 10, 2023

By default, cron doesn't log the output or exit code from your cron jobs, only that they were started. This guide will cover a simple technique to capture and save job output and error messages to a log file.

Logging the output of a cron job

It's a common practice for cron jobs to write important debugging and verification details to stdout and stderr, usually with print or echo statements from within the code. This is the text you see in your terminal when you run the job from the command line. To save the output of your cron job to a file, modify the crontab line to redirect your job's stdout and stderr to a file of your choice. Here is a simple before and after to show how you can add logging to a cron job:

# Before
$ crontab -l
*/5 * * * * python /home/crons/send-updates.py

# After
$ crontab -l 
*/5 * * * * python /home/crons/send-updates.py >> /home/crons/send-updates.log 2>&1

Breaking this down, we are first using >>, the output redirection operator, which captures the output of the command to the left of it, and writes it to the log file that the arrow is point to. We give the full path to a log file, and then, at the end, the 2>&1 tells the shell that you want to combine any messages written to stderr with the messages written to stdout, so both are captured together in the same log.

Note: In this case, we are using >> which will append to the logfile. When a single arrow > is used, the logfile will always be overwritten with the most recent result.

If you are a Cronitor user, complete cron job output is automatically captured without any additional crontab changes. To view complete logs from any execution, select the job from your dashboard, find the execution in the Latest Activity panel, and click it to see the captured logs.

Want alerts if your cron jobs stop working?

Monitor your cron jobs with Cronitor to easily collect output, capture errors and alert you when something goes wrong.