Leveraging syslog for cron scripts
I have written a bunch of scripts to automate some tasks, like for example to automate dynamic IP registration in a DNS or more commonly for backup purposes.
If you look at those scrits, you will notice that I never neglect the logging piece, and the way I have been doing it so far is through redirection of STDERR and STDOUT to files, prefixing the info with some date tags. I just came to realize there is a much more elegant way to do this using
Now, in my scripts, the logging is simply done using echo commands in plain form (no prefix of timestamps, etc.) and the tasks are invoqued in
crontab as follows :
*/5 * * * * /usr/local/bin/dyndns.sh 2>&1 | /usr/bin/logger -t dyndns
What this will do is send the STDERR and STDOUT of the cron script in through
syslog magic, where one can make extensively use of filters and automated log rotation. The
-t dyndns part will tag the message with
dyndns (basically a keyword of my choice), to make it easier to spot in the
/var/log/message file. But wait, there’s more! It is super easy to have this script use its own log file as well, by simply creating a file
/etc/rsyslog.d/00-dyndns.conf with the following content:
:syslogtag, isequal, "dyndns:" /var/log/dyndns.log & ~
Basically the first line says messages that are tagged with dyndns should be sent to /var/log/dyndns.log, and the second lines says that no more filters should be applied for these lines. Note that if you use a separate log file, you must configure
The full monthy of rules and more rsyslog bonanza can be found on the rsyslog official website.