Logging Cron Jobs
I love cron but I've often used it for non-critical things and just hoped it worked. No more!
I read this Server Fault post that helped me log cron jobs with a tag:
*/20 * * * * /home/user/repos/scripts/check_status_and_notify.sh 2>&1 | /usr/bin/logger -t status_check
Then you can check the output of the commands by running:
grep status_check /var/log/syslog
No more wondering if it ran.
What's 2>&1?
This redirects UNIX stderr to stdout, allowing us to also log stderr. See this Super User post.
Still, it's easier to understand what this is doing by running actual commands. Here pyproject.toml is a file that exists in the directory, whereas missing.txt does not:
``` username@os:~/repos$ ls pyproject.toml missing.txt ls: cannot access 'missing.txt': No such file or directory pyproject.toml
username@os:~/repos$ ls pyproject.toml missing.txt > dirlist 2>&1
username@os:~/repos$ cat dirlist ls: cannot access 'missing.txt': No such file or directory pyproject.toml
username@os:~/repos$ ls pyproject.toml missing.txt > dirlist2 ls: cannot access 'missing.txt': No such file or directory
username@os:~/repos$ cat dirlist2 pyproject.toml ```
As you can see, the 2>&1 also writes stderr to the file, whereas the simple > redirect writes stdout to the file and stderr to the terminal.