Crontab Log – How to log the Output of a Cron Script (and email it as well)

cron-logo-680x225 As mentioned earlier, in my world of development, I keep landing myself into sticky situations and what makes me keep my job or clients happy is that I get myself out of such sticky situations quick quickly. Now, the situation I encountered recently involved crons

I have a php script whose function is to check a certain database for messages to be sent. The script should then collect required messages and pass them on the the Goip SMS gateway. Now, how do I save the output of the sending to the gateway so that I can know which ones failed – if any – without having to add the logging function into the sending script and without having to look through cron’s own logs? Answer – simply tweak the cron command slightly to achieve logging.

Lets say you have a php script sms.php to execute everyday at 10 am

0 10 * * * php –q /var/www/htdocs/sms.php

In general, if the script throws any output (including errors), you might want to log this. To do this, modify the entry as shown below to ass output and error redirection.

0 10 * * * php –q /var/www/htdocs/sms.php >> /var/www/htdocs/sms.log 2>&1

In the above example,

  • > /var/www/htdocs/sms.log indicates that the standart output of the script is to be redirected to the sms.log file
  • 2>&1 indicates that standard errors are also redirected to the same file descriptor that

Should you need to get email responces as well, append | mail –s “subject for email” email@domain.tld to the cron command. So you can end up with the following

0 10 * * * php –q /var/www/htdocs/sms.php >> /var/www/htdocs/sms.log 2>&1 | mail –s “subject for email” email@domain.tld

It should be noted that the >> in the command will append to the log file. Should you want to overwrite the log file each time the cron runs, use > instead.

Questions?

Share

Leave a Reply