Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stderr with date to log file from Cron

A bash script is run from cron, stderr is redirected to a logfile, this all works fine. The code is:

*/10 5-22 * * * /opt/scripts/sql_fetch 2>> /opt/scripts/logfile.txt

I want to prepend the date to every line in the log file, this does not work, the code is:

*/10 5-22 * * * /opt/scripts/sql_fetch 2>> ( /opt/scripts/predate.sh >> /opt/scripts/logfile.txt )

The predate.sh script looks as follows:

#!/bin/bash
while read line ; do
    echo "$(date): ${line}"
done

So the second bit of code doesn't work, could someone shed some light? Thanks.

like image 405
kingmilo Avatar asked Aug 22 '11 09:08

kingmilo


2 Answers

I have a small script cronlog.sh to do this. The script code

#!/bin/sh
echo "[`date`] Start executing $1"
$@ 2>&1 | sed -e "s/\(.*\)/[`date`] \1/"
echo "[`date`] End executing $1"

Then you could do

cronlog.sh /opt/scripts/sql_fetch >> your_log_file

Example result

cronlog.sh echo 'hello world!'

[Mon Aug 22 04:46:03 CDT 2011] Start executing echo
[Mon Aug 22 04:46:03 CDT 2011] helloworld!
[Mon Aug 22 04:46:03 CDT 2011] End executing echo
like image 96
Ryan Ye Avatar answered Sep 18 '22 09:09

Ryan Ye


*/10 5-22 * * * (/opt/scripts/predate.sh; /opt/scripts/sql_fetch 2>&1) >> /opt/scripts/logfile.txt

should be exactly your way.

like image 35
glglgl Avatar answered Sep 19 '22 09:09

glglgl