Cron Logging & Output

Capture, redirect, and monitor cron job output effectively.

Best Practice: Always capture cron output for debugging and monitoring. Silent failures are hard to diagnose.

Output Redirection

Basic Logging

# Append stdout to log file 0 2 * * * /path/to/script.sh >> /var/log/backup.log # Redirect both stdout and stderr 0 2 * * * /path/to/script.sh >> /var/log/backup.log 2>&1 # Separate stdout and stderr 0 2 * * * /path/to/script.sh >> /var/log/backup.log 2>> /var/log/backup-errors.log

Advanced Logging

# Log with timestamp 0 2 * * * echo "$(date): Starting backup" >> /var/log/backup.log && /path/to/script.sh >> /var/log/backup.log 2>&1 # Rotating logs (overwrite instead of append) 0 2 * * * /path/to/script.sh > /var/log/backup-$(date +\%Y\%m\%d).log 2>&1

Email Notifications

MAILTO Variable

# Send all output to email [email protected] # Send only errors 0 2 * * * /path/to/script.sh > /dev/null # Disable all email MAILTO=""

Structured Logging

Logging Script Template

#!/bin/bash # /opt/scripts/log-wrapper.sh LOGFILE="/var/log/cron-jobs.log" SCRIPT="$1" echo "$(date '+%Y-%m-%d %H:%M:%S'): Starting $SCRIPT" >> "$LOGFILE" # Run the actual script and capture exit code "$SCRIPT" >> "$LOGFILE" 2>&1 EXIT_CODE=$? echo "$(date '+%Y-%m-%d %H:%M:%S'): Finished $SCRIPT (exit code: $EXIT_CODE)" >> "$LOGFILE" exit $EXIT_CODE

Usage: 0 2 * * * /opt/scripts/log-wrapper.sh /path/to/your-script.sh