2013-04-30 110 views
1

/var/log/httpd/error_log文件,其中包含整個httpd的錯誤。發送附帶最新文件內容的郵件

我希望能夠通過電子郵件發送這些新日誌(如果有) - 例如間隔15分鐘。我想用CRON來調用將發送新內容的bash腳本。

是否有任何有效的方法來獲取,自上次檢查後追加了哪些行?

回答

2

當發送郵件,你可以存儲文件的行數的地方(例如,文件),然後用tail +n只從第n行打印,就像

last_linecount=`cat .last_linecount` # or check if file does not exist 
wc -l /var/log/httpd/error_log >.last_linecount 
tail -n +$((last_linecount + 1)) /var/log/httpd/error_log | whatever 

你還應檢查當前行數是否低於last_linecount,因爲日誌文件可能已被輪換(如果適用),您必須將舊日誌文件中的尾部和新日誌文件中的所有內容組合起來。

2

您可以使用error_log作爲標記,並且不需要在外部文件中存儲行號。

下一個腳本:

#!/bin/bash 

STRING="last_log_check_point_string" 
LOGFILE="/opt/local/apache2/logs/error_log" 
URL="http://localhost/$STRING" 

linenum=$(grep -n "$STRING" $LOGFILE | tail -1 | sed 's/:.*//') 
curl "${URL}" >/dev/null 2>&1 
[[ ! -z "$linenum" ]] && sed -n "$linenum,\$p" < $LOGFILE | mail -s "error log at $(date)" "[email protected]" 
  • 會發現last_log_check_point_string
  • 的最後一次出現的行號將與不存在的網址是什麼包含您的字符串到您的網頁的請求(這樣,你會得到一個新的通知到error_log - 新的marker_point
  • 以上每條線行號會郵寄給你。

error_log的最後一行將是新的marker point,因此您可以控制腳本的工作方式。如果您沒有curl,請使用wget - 或者也可以用純粹的bash發出請求。

或變種 - 你會得到電子郵件,只有當某些錯誤發生

#!/bin/bash 

STRING="last_log_check_point_string" 
LOGFILE="/opt/local/apache2/logs/error_log" 
URL="http://localhost/$STRING" 
TEMPFILE="/tmp/hterror.$$" 

linenum=$(grep -n "$STRING" $LOGFILE | tail -1 | sed 's/:.*//') 
curl "${URL}" >/dev/null 2>&1 
[[ ! -z "$linenum" ]] && sed -n "$linenum,\$p" < $LOGFILE | grep -v "$STRING" >$TEMPFILE 
[[ -s "$TEMPFILE" ]] && mail -s "error log at $(date)" "[email protected]" < $TEMPFILE 
rm -f "$TEMPFILE" 
相關問題