Linux?Shell實現(xiàn)日志監(jiān)控與報警系統(tǒng)
1.日志監(jiān)控基礎(chǔ)
監(jiān)控文件變化:
- tail -f:實時查看文件末尾的變化。
- tail -n:指定查看最近的 N 行。
結(jié)合管道過濾關(guān)鍵內(nèi)容:
配合grep 提取特定關(guān)鍵字。
例子:
tail -f /var/log/syslog | grep "error"
2.日志文件滾動
了解日志文件的滾動機制(如日志按大小或時間切割)。
使用logrotate 進行日志管理。
3.實時報警機制
結(jié)合awk 提取特定模式并觸發(fā)報警。
郵件報警:
使用mail 或sendmail 命令發(fā)送郵件。
終端提示:
使用echo 和notify-send。
例子:
tail -f application.log | awk '/ERROR/ {print "Error detected: "$0}'
4.復雜監(jiān)控場景
多關(guān)鍵字匹配與分級報警。
監(jiān)控多文件并聚合結(jié)果。
5.實驗例子
實驗 1: 簡單日志監(jiān)控
目標:實時監(jiān)控一個日志文件并提取含有 "ERROR" 的行。
實驗代碼:
#!/bin/bash logfile="application.log" if [[ ! -f $logfile ]]; then echo "Log file not found: $logfile" exit 1 fi echo "Monitoring $logfile for 'ERROR'..." tail -f $logfile | grep "ERROR"
實驗 2: 動態(tài)監(jiān)控日志并發(fā)送報警
目標:檢測日志文件中的錯誤信息,并在終端顯示報警。
實驗代碼:
#!/bin/bash
logfile="application.log"
if [[ ! -f $logfile ]]; then
echo "Log file not found: $logfile"
exit 1
fi
monitor_log() {
tail -f $logfile | while read line; do
if echo "$line" | grep -q "ERROR"; then
echo "[ALERT] $(date): $line"
fi
done
}
monitor_log
實驗 3: 日志關(guān)鍵字分級報警
目標:根據(jù)日志內(nèi)容分類報警,如 "ERROR" 觸發(fā)高優(yōu)先級報警,"WARNING" 觸發(fā)普通報警。
實驗代碼:
#!/bin/bash
logfile="application.log"
if [[ ! -f $logfile ]]; then
echo "Log file not found: $logfile"
exit 1
fi
tail -f $logfile | while read line; do
if echo "$line" | grep -q "ERROR"; then
echo "[HIGH PRIORITY ALERT] $(date): $line"
elif echo "$line" | grep -q "WARNING"; then
echo "[Warning] $(date): $line"
fi
done
實驗 4: 監(jiān)控多日志文件
目標:同時監(jiān)控多個日志文件,并合并結(jié)果。
實驗代碼:
#!/bin/bash
logfiles=("/var/log/syslog" "/var/log/auth.log")
for logfile in "${logfiles[@]}"; do
if [[ -f $logfile ]]; then
tail -f $logfile | awk -v log=$logfile '{print "["log"] "$0}' &
else
echo "File not found: $logfile"
fi
done
wait
實驗 5: 定制報警系統(tǒng)
目標:基于日志信息發(fā)送郵件通知。
實驗代碼:
#!/bin/bash
logfile="application.log"
email="admin@example.com"
if [[ ! -f $logfile ]]; then
echo "Log file not found: $logfile"
exit 1
fi
tail -f $logfile | while read line; do
if echo "$line" | grep -q "CRITICAL"; then
echo "Critical alert detected: $line" | mail -s "Critical Alert" $email
echo "Email sent for alert: $line"
fi
done
6.實操
編寫腳本監(jiān)控/var/log/syslog,提取含有 "Failed" 的行并統(tǒng)計次數(shù)。
#!/bin/bash
logfile="/var/log/syslog"
count=0
if [[ ! -f $logfile ]]; then
echo "Log file not found: $logfile"
exit 1
fi
echo "Monitoring $logfile for 'Failed'..."
tail -f $logfile | while read line; do
if echo "$line" | grep -q "Failed"; then
count=$((count + 1))
echo "$line"
echo "Total 'Failed' entries: $count"
fi
done
實現(xiàn)一個腳本監(jiān)控指定文件夾的文件增長情況。
#!/bin/bash
monitor_dir="/path/to/your/directory"
if [[ ! -d $monitor_dir ]]; then
echo "Directory not found: $monitor_dir"
exit 1
fi
echo "Monitoring file changes in $monitor_dir..."
prev_count=$(ls "$monitor_dir" | wc -l)
while true; do
current_count=$(ls "$monitor_dir" | wc -l)
if [[ $current_count -ne $prev_count ]]; then
echo "$(date): File count changed from $prev_count to $current_count"
prev_count=$current_count
fi
sleep 2
done
將實驗 3 的代碼改進,支持通過配置文件指定關(guān)鍵字和報警級別。
#!/bin/bash
logfile="application.log"
config_file="keywords.conf"
if [[ ! -f $logfile ]]; then
echo "Log file not found: $logfile"
exit 1
fi
if [[ ! -f $config_file ]]; then
echo "Config file not found: $config_file"
exit 1
fi
declare -A keywords
while IFS=: read -r keyword level; do
keywords["$keyword"]=$level
done < "$config_file"
tail -f $logfile | while read line; do
for keyword in "${!keywords[@]}"; do
if echo "$line" | grep -q "$keyword"; then
echo "[${keywords[$keyword]} PRIORITY] $(date): $line"
fi
done
done
使用tail -f 和awk 實現(xiàn)實時日志監(jiān)控,統(tǒng)計日志中每分鐘的訪問次數(shù)。
#!/bin/bash
logfile="access.log"
if [[ ! -f $logfile ]]; then
echo "Log file not found: $logfile"
exit 1
fi
echo "Monitoring $logfile for access counts per minute..."
tail -f $logfile | awk '
{
timestamp = substr($4, 2, 17) # 提取時間戳,格式化為 "dd/MMM/yyyy:HH:mm"
split(timestamp, time_parts, ":")
minute = time_parts[1] ":" time_parts[2] # 僅保留到分鐘
access_counts[minute]++
print "Access count for " minute ": " access_counts[minute]
}'
編寫腳本實現(xiàn)對超過指定大小的日志文件進行自動歸檔和壓縮。
#!/bin/bash
logfile="application.log"
max_size=1048576 # 1 MB in bytes
archive_dir="archives"
mkdir -p "$archive_dir"
while true; do
if [[ -f $logfile ]]; then
log_size=$(stat -c%s "$logfile")
if (( log_size > max_size )); then
timestamp=$(date +'%Y%m%d_%H%M%S')
mv "$logfile" "$archive_dir/application_$timestamp.log"
gzip "$archive_dir/application_$timestamp.log"
echo "Archived and compressed $logfile at $timestamp"
> "$logfile" # 清空原日志文件
fi
fi
sleep 10
done到此這篇關(guān)于 Linux Shell實現(xiàn)日志監(jiān)控與報警系統(tǒng)的文章就介紹到這了,更多相關(guān)Shell日志監(jiān)控與報警內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux多線程編程詳解教程(線程通過信號量實現(xiàn)通信代碼)
這篇文章主要介紹了linux多線程編程詳解教程,提供線程通過信號量實現(xiàn)通信的代碼,大家參考使用吧2013-12-12
阿里云云服務器Linux系統(tǒng)更新yum源Shell腳本
這篇文章主要介紹了阿里云云服務器Linux系統(tǒng)更新yum源Shell腳本,阿里云自建了一個包含大多數(shù)系統(tǒng)更新的本地yum源,速度快又好用,需要的朋友可以參考下2014-09-09

