Redirect stderr with date to log file from Cron

旧巷老猫 提交于 2019-12-19 04:07:52

问题


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.


回答1:


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



回答2:


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

should be exactly your way.



来源:https://stackoverflow.com/questions/7145544/redirect-stderr-with-date-to-log-file-from-cron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!