الملفات
Task_api/monitor (copy 1).sh

43 أسطر
1.4 KiB
Bash
خام اللوم التاريخ

هذا الملف يحتوي على أحرف Unicode غير مرئية

هذا الملف يحتوي على أحرف Unicode غير مرئية لا يمكن التمييز بينها بعين الإنسان ولكن قد تتم معالجتها بشكل مختلف بواسطة الحاسوب. إذا كنت تعتقد أن هذا مقصود، يمكنك تجاهل هذا التحذير بأمان. استخدم زر الهروب للكشف عنها.

#!/usr/bin/env bash
# monitor.sh — íÑÕÏ api.log áÇßÊÔÇÝ ÃÎØÇÁ 4xx/5xx Ãæ ßáãÇÊ failed/timeout
# æíÑÓá JSON Åáì CLOUD endpoint ÚÈÑ curl
LOGFILE="./api.log"
CLOUD_ENDPOINT="${CLOUD_ENDPOINT:-https://example.com/alert}"
if [ ! -f "$LOGFILE" ]; then
echo "api.log not found, creating..."
touch "$LOGFILE"
fi
tail -n0 -F "$LOGFILE" | while read -r line; do
echo "$line" | grep -E "ERROR|4[0-9]{2}|5[0-9]{2}|failed|timeout" >/dev/null 2>&1
if [ $? -eq 0 ]; then
ts=$(date --iso-8601=seconds)
ip=$(hostname -I 2>/dev/null | awk '{print $1}')
cpu_line=$(top -bn1 | grep "Cpu(s)" 2>/dev/null || top -bn1 | head -n 5 | tail -n 1)
ram_line=$(free -m | awk 'NR==2{printf "%sMB/%sMB (used/total)", $3,$2}')
disk_line=$(df -h / | awk 'NR==2{print $3" used of " $2 " (" $5 " used)"}')
log_excerpt="$line"
# ÓæöøÑ JSON (ÇÍÐÑ ÚáÇãÇÊ ÇáÇÞÊÈÇÓ)
payload=$(cat <<EOF
{
"timestamp": "$ts",
"server_ip": "$ip",
"cpu": "$(echo "$cpu_line" | sed 's/\"/'"'"'/g')",
"ram": "$ram_line",
"disk": "$disk_line",
"log_line": "$(echo "$log_excerpt" | sed 's/\"/'"'"'/g')"
}
EOF
)
echo "[$ts] ALERT: sending payload to $CLOUD_ENDPOINT"
curl -s -X POST -H "Content-Type: application/json" -d "$payload" "$CLOUD_ENDPOINT" || {
echo "[$(date --iso-8601=seconds)] Failed to send alert" >&2
}
fi
done