求助:通过Crontab每30分钟执行日志ERROR扫描及邮件告警脚本
Hey Casey, let's build a reliable, automated solution for your requirement—here's how to set up a crontab task that scans the last 30 minutes of logs, captures ERROR lines (and their surrounding context), and emails them to you:
Step 1: Create a Reusable Shell Script
Instead of cramming all logic into a single crontab line (which gets messy with quotes and variables), create a dedicated script. Save this as check_error_logs.sh:
#!/bin/bash # Configure these variables to match your environment LOG_FILE="/full/path/to/debug.log" # Replace with your actual log file path RECIPIENT_EMAIL="your.email@example.com" # Replace with your target email # Calculate dynamic time range (last 30 minutes to now) # Matches the YYYY-MM-DD HH:MM format from your log example START_TIME=$(/usr/bin/date -d "-30 minutes" +"%Y-%m-%d %H:%M") END_TIME=$(/usr/bin/date +"%Y-%m-%d %H:%M") # Extract logs from the time range, filter ERRORs with 3 lines of context error_output=$(/usr/bin/sed -n "/$START_TIME/,/$END_TIME/p" "$LOG_FILE" | /usr/bin/grep -A 3 -B 3 "ERROR") # Only send email if there are ERRORs (optional but reduces noise) if [ -n "$error_output" ]; then echo "$error_output" | /usr/bin/mail -s "[$(/usr/bin/date '+%Y-%m-%d %H:%M')] 30-Minute ERROR Log Alert" "$RECIPIENT_EMAIL" else # Optional: Uncomment below to send a "no errors" notification # echo "No ERROR entries found in the last 30 minutes." | /usr/bin/mail -s "[$(/usr/bin/date '+%Y-%m-%d %H:%M')] No ERROR Logs" "$RECIPIENT_EMAIL" fi
Step 2: Make the Script Executable
Run this command to grant execution permissions to the script:
chmod +x /full/path/to/check_error_logs.sh
Step 3: Configure Crontab
Open your crontab editor with:
crontab -e
Add this line to schedule the script to run every 30 minutes:
*/30 * * * * /full/path/to/check_error_logs.sh >> /var/log/error_monitor_cron.log 2>&1
The >> /var/log/error_monitor_cron.log 2>&1 part logs any cron task errors to a dedicated file, which simplifies debugging if the task fails.
Key Notes & Troubleshooting Tips
- Time Format Matching: Double-check that your log's timestamp format exactly matches
YYYY-MM-DD HH:MM(two digits for minutes). If your logs use single-digit minutes (e.g.,11:5instead of11:05), adjust thedatecommand to use a regex-friendly format likeSTART_TIME=$(/usr/bin/date -d "-30 minutes" +"%Y-%m-%d %H:")and modify the sed command to/\$START_TIME[0-5][0-9]/,/\$END_TIME[0-5][0-9]/p. - Email Setup: Ensure your system has a mail transfer agent (MTA) like Postfix or Sendmail installed and configured. Test the
mailcommand manually first to confirm it can send emails successfully. - Absolute Paths: Always use full paths for commands (e.g.,
/usr/bin/dateinstead ofdate) in cron scripts—cron uses a minimal environment and may not recognize your usual PATH variables. - Context Lines: The
grep -A 3 -B 3flag captures 3 lines after and before each ERROR. Adjust the numbers if you need more or less surrounding context.
内容的提问来源于stack exchange,提问作者Casey

