How to start logging cron job output to syslog on Ubuntu 20.04?

Better Stack Team
Updated on May 4, 2022

Cron can generate logs, which are very useful in troubleshooting your cron jobs. If your cron job generates some output, it's collected and sent to you via email. But you may want to send this collected output to the system log instead.

Why is it helpful you may ask. Well, if all cron job outputs are in one place, it's easier to go through all of them at once as you don't need to switch between directories back and forward. Also, you can display cron outputs using a single command, isn't that cool?

In this quick tutorial, we will take a look at how to redirect output from cron jobs to the main system log.

Where does the cron job output go?

Let's take a look at this example. Imagine that you have the following cron job defined in your crontab:

*/10 * * * * /home/user/myscript.sh
Copied!

This cron job runs every 10 minutes and executes /home/user/myscript.sh shell script. The output of this script will be collected and cron will try to send it to you via email. That means you will only see the following logs in the syslog:

Nov 11 12:00:00 server CRON[1011]: (user) CMD (/home/user/myscript.sh)
Nov 11 12:00:00 server CRON[1009]: (CRON) info (No MTA installed, discarding output
Copied!

Syslog will only show that the /home/user/myscript.sh shell script was executed successfully and that the output of this script was discarded to the missing MTA (Message transfer agent). The output of the script will not be present in the syslog.

How to send cron job output to syslog?

Now, let's redirect the output of the /home/user/myscript.sh shell script to the syslog by changing the crontab to the following:

*/10 * * * * /home/user/myscript.sh 2>&1 | /usr/bin/logger -t CRONOUTPUT
Copied!

Let's break down this code:

  • /10 * * * * This part states that the cron job will run every 10 minutes
  • /home/user/myscript.sh Script that will be executed
  • 2>&1 This will forward errors to standard output
  • | /usr/bin/logger -t CRONOUTPUT This will pipe (forward) standard output to syslog with the name CRONOUTPUT

Now, you can display the output of the cron job in the system log and filter it using the following command:

cat /var/log/syslog | grep CRONOUTPUT
Copied!
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack