附加到日志文件的顶部

附加到日志文件的顶部

我有一个 crontab 脚本,用于监视两台计算机之间的灾难恢复进程,并且该脚本生成一个日志文件。我被要求做的基本上是将生成的新日志附加在前一个日志的顶部(因为我使用相同的文件名)而不是底部。

我已经看到了很少的选择,但我所有的尝试都失败了。

我尝试过

cat $LOGFILE >> $TEMPLOG
rm $LOGFILE
mv -i $TEMPLOG $LOGFILE

并且还与

cat - $LOGFILE > $TEMPLOG && mv $TEMPLOG $LOGFILE

变量 $LOGFILE 是脚本附加进程的每个语句的位置。

谢谢 :)

基本上我想做的是在通过邮件发送之前在最后一次运行的顶部生成正确的日志。

DATE=`date "+%d%m%y_%H%M"`
PRIMARY_HOSTNAME=`hostname`
LOGFILE=/dba/logs/monitor_sync_FM2.log
TEMPLOG=/dba/logs/monitor_sync_LOG.log
SERVER=`hostname`
SITE=mycompany
EMAILTO="[email protected]"
DBOPS="oracle@${SERVER}.${SITE}"

export PRIMARY_HOSTNAME LOGFILE TEMPLOG SERVER SITE EMAILTO DBOPS DATE
echo "\n\n### monitor DR sync  started @ `date` ###" >> $LOGFILE
echo "Running SQL command to verify latest SCN.." >> $LOGFILE
echo "The current SCN of the Primary DB server is: $PRIMARY_CURRENT_SCN" >> $LOGFILE

echo "Connecting now to the secondary standby database server..." >> $LOGFILE
SECONDARY_CURRENT_SCN=`ssh [email protected] /home/oracle/script_sync2.sh` >> $LOGFILE
export SECONDARY_CURRENT_SCN
echo "Secondary SCN output returned as: $SECONDARY_CURRENT_SCN" >> $LOGFILE
grep ORA- /dba/scripts/output.txt
if [ $? = 0 ]; then
echo "Remote ssh command to Secondary server failed..Exiting" >> $LOGFILE
echo "### monitor DR sync failed @ `date` ###" >> $LOGFILE
echo "PROBLEM" >> $LOGFILE

mailx -r ${DBOPS} -s "PROBLEM" ${EMAILTO} < $LOGFILE
exit
else
echo "The current SCN of the Secondary DB server is: $SECONDARY_CURRENT_SCN" >> $LOGFILE
DIFF=`expr $PRIMARY_CURRENT_SCN - $SECONDARY_CURRENT_SCN` ; export DIFF
if [ $PRIMARY_CURRENT_SCN -ne $SECONDARY_CURRENT_SCN ]; then
        echo "The difference is $DIFF" >> $LOGFILE
        if [ `echo $DIFF` -gt 3 ]; then
                echo "Log Gap: $DIFF" >> $LOGFILE
                                echo "PROBLEM" >> $LOGFILE
                                echo "### script finished @ `date` ###\n\n" >> $LOGFILE
                mailx -r ${DBOPS} -s "PROBLEM" ${EMAILTO}  < ${LOGFILE}
        else
                                echo "SUCCESS" >> $LOGFILE
                mailx -r ${DBOPS} -s "SUCCESS" ${EMAILTO}  < ${LOGFILE}
                echo "Log Gap: $DIFF" >> $LOGFILE
        fi
else
echo "Log Gap: $DIFF" >> $LOGFILE
echo "SUCCESS" >> $LOGFILE
mailx -r ${DBOPS} -s "SUCCESS" ${EMAILTO}  < ${LOGFILE}
fi
fi

答案1

如果您想将当前运行的日志“附加”(插入)到现有日志文件的开头,那么请继续尝试使用 TEMPLOG 文件。将脚本的所有输出/数据写入该 $TEMPLOG 文件,然后执行以下操作:

ed -s $LOGFILE <<< "0r $TEMPLOG"$'\n'wq

在第 0 行之后将r$TEMPLOG 写入 $LOGFILE。

举个例子:

$ cat logfile
previous
entries
here
$ cat templog
New
Entry goes
Here
$ ed -s "$LOGFILE" <<< "0r $TEMPLOG"$'\n'wq
$ cat logfile
New
Entry goes
Here
previous
entries
here

如果您的 shell 不支持 here-strings,请改为将指令打印到 ed 的 stdin:

printf "0r $TEMPLOG\nwq\n" | ed -s logfile

如果您只需要以下内容电子邮件要更改,而不是 $LOGFILE 本身,只需将其添加到邮件管道中即可:

cat "$TEMPLOG" "$LOGFILE" | mailx -r ${DBOPS} -s "SUCCESS" ${EMAILTO}

答案2

由于您的脚本附加到$LOGFILE,我认为您想要的是

mv $LOGFILE $TEMPLOG

在开始时和

cat $TEMPLOG >>$LOGFILE

就在邮寄之前。

相关内容