Linux Basic — Logging Cron Output

1 minute read

Logging Cron Output

By default, cron emails stdout/stderr. For production automation, you want logs in files or syslog — persistent, searchable, and rotated.


Redirect to a Log File

0 2 * * * /opt/backup.sh >> /var/log/backup.log 2>&1
  • >> appends (don’t truncate on each run)
  • 2>&1 sends stderr to stdout, so both go to the log

Separate stdout and stderr

0 2 * * * /opt/backup.sh >> /var/log/backup.log 2>> /var/log/backup-error.log

Review backup-error.log for failures.


Use logger for syslog

logger sends messages to syslog (/var/log/syslog or journalctl):

#!/usr/bin/env bash
logger -t backup "starting backup"
# ... do work
logger -t backup "backup complete"

In cron:

0 2 * * * /opt/backup.sh 2>&1 | logger -t backup

All output goes to syslog with the tag backup.


Combine: File + Email on Failure

#!/usr/bin/env bash
exec > >(tee -a /var/log/backup.log)
exec 2>&1

# ... script body

if [[ $? -ne 0 ]]; then
    echo "FAILURE" | mail -s "Backup failed" ops@example.com
fi

Or in cron:

0 2 * * * /opt/backup.sh >> /var/log/backup.log 2>&1 || echo "backup failed" | mail -s ALERT ops@example.com

Rotate Cron Logs with logrotate

Add /etc/logrotate.d/myapp:

/var/log/backup.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
}

logrotate runs from cron daily and keeps the last 7 compressed logs.


Timestamped Log Helper

For inline timestamps:

log() { echo "$(date '+%F %T') $*"; }
log "starting backup"

Or prepend every line:

exec > >(ts '[%F %T]' | tee -a /var/log/backup.log)
exec 2>&1

(ts from moreutils package)


Next → Practice Exercises

Updated: