簡體   English   中英

使用 wget 每 5 分鍾下載一次日志文件並檢測更改

[英]using wget to download log file every 5 mins & detect changes

我正在編寫一個 bash 腳本來完成以下任務。

  1. 腳本每五分鍾運行一次 wget 以從靜態 url 下載一個小日志。
  2. 腳本使用 diff 來查看日志文件中是否有任何新條目(新條目在日志文件末尾創建)。
  3. 如果找到新的日志條目 - 將新條目提取到新文件中,正確格式化它們,向我發送警報,返回 #1。
  4. 如果沒有找到新的日志條目,請返回 #1。
wget "https://url-to-logs.org" -O new_log
if diff -q new_log old_log; then
echo "no new log entries to send."
else
echo "new log entries found, sending alert."
diff -u new_log old_log > new_entries

#some logic i have to take the output of "new_entries", properly format the text and send the alert.

rm -rf old_log new_entries
cp new_log old_log
rm -rf new_log
fi

還有一件事 - 每晚午夜,托管日志的服務器都會刪除所有條目並顯示一個空白文件,直到為新的一天創建新的日志條目。

我想我總是可以在午夜運行一個 cron 作業來運行“rm -rf”並“觸摸”old_log 文件,但很好奇是否存在更簡單的方法。

提前感謝任何/所有輸入和幫助。

如果您的日志沒有輪換 - 即舊日志保證是新日志的前綴,您可以使用tail獲取新后綴 - 如下所示:

tail -n+$(( $(wc -l old_log) + 1 )) new_log > new_entries

如果new_log中沒有新行,則new_entries文件將為空,您可以使用stat或其他方式檢查。

如果您的日志正在輪換,您應該首先使用grep檢查舊日志的最后一行是否存在於新日志中,如果不存在 - 假設整個新日志是新的:


if ! egrep -q "^$(tail -n1 old_log)\$" new_log; then cat new_log > new_entries; fi

如果日志文件中的所有行都是唯一的,那么您可以使用grep

wget "https://url-to-logs.org" -O new_log || exit 1

if new_entries=$(grep -vxFf old_log new_log)
then
    # format and send alert
    printf '%s\n' "$new_entries"
fi

mv -f new_log old_log

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM