84 أسطر
2.0 KiB
Bash
ملف تنفيذي
84 أسطر
2.0 KiB
Bash
ملف تنفيذي
#!/bin/bash
|
|
|
|
# Configuration
|
|
LOG_FILE="api.log"
|
|
GHAYMAH_URL="GHAYMAH_ENDPOINT_HERE" # don't forget to edit it
|
|
|
|
echo "Starting log monitor..."
|
|
echo "Watching file: $LOG_FILE"
|
|
|
|
# Check if log file exists
|
|
if [ ! -f "$LOG_FILE" ]; then
|
|
echo "Warning: $LOG_FILE not found. Creating it..."
|
|
touch "$LOG_FILE"
|
|
fi
|
|
|
|
# Function to get server info
|
|
get_server_info() {
|
|
# Get IP address
|
|
IP=$(hostname -I | awk '{print $1}')
|
|
|
|
# Get CPU usage
|
|
CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1)
|
|
|
|
# Get available RAM
|
|
RAM=$(free -h | grep Mem | awk '{print $7}')
|
|
|
|
# Get available disk space
|
|
DISK=$(df -h / | tail -1 | awk '{print $4}')
|
|
|
|
echo "$IP|$CPU|$RAM|$DISK"
|
|
}
|
|
|
|
# Function to send alert
|
|
send_alert() {
|
|
ERROR_MSG=$1
|
|
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
# Get server metrics
|
|
SERVER_INFO=$(get_server_info)
|
|
IP=$(echo $SERVER_INFO | cut -d'|' -f1)
|
|
CPU=$(echo $SERVER_INFO | cut -d'|' -f2)
|
|
RAM=$(echo $SERVER_INFO | cut -d'|' -f3)
|
|
DISK=$(echo $SERVER_INFO | cut -d'|' -f4)
|
|
|
|
# Create JSON payload
|
|
JSON_PAYLOAD=$(cat <<EOF
|
|
{
|
|
"error": "$ERROR_MSG",
|
|
"timestamp": "$TIMESTAMP",
|
|
"message": "Error detected in API logs",
|
|
"server_metrics": {
|
|
"ip": "$IP",
|
|
"cpu_usage": "${CPU}%",
|
|
"ram_available": "$RAM",
|
|
"disk_space": "$DISK"
|
|
}
|
|
}
|
|
EOF
|
|
)
|
|
|
|
echo "Alert detected: $ERROR_MSG"
|
|
echo "Server IP: $IP | CPU: ${CPU}% | RAM: $RAM | Disk: $DISK"
|
|
|
|
# Send to Ghaymah endpoint
|
|
# do not Uncomment without the endpoint
|
|
# curl -X POST "$GHAYMAH_URL" \
|
|
# -H "Content-Type: application/json" \
|
|
# -d "$JSON_PAYLOAD"
|
|
|
|
# For now, just save to alert file
|
|
echo "$JSON_PAYLOAD" >> alerts.log
|
|
echo "Alert saved to alerts.log"
|
|
}
|
|
|
|
# Monitor log file continuously
|
|
tail -f "$LOG_FILE" | while read line
|
|
do
|
|
# Check for error patterns
|
|
if echo "$line" | grep -E "(ERROR|400|404|500|failed|timeout)" > /dev/null; then
|
|
echo "Error found: $line"
|
|
send_alert "$line"
|
|
fi
|
|
done
|