#!/bin/bash
# Enterprise log error detection script
# Searches multiple log files for common error patterns
LOG_DIR=${1:-/var/log}
SEARCH_PATTERNS=(
"ERROR"
"FATAL"
"CRITICAL"
"Exception"
"Failed"
"denied"
"timeout"
"connection refused"
)
OUTPUT_FILE="error_report_$(date +%Y%m%d_%H%M%S).txt"
find_errors() {
local log_file=$1
local pattern=$2
if [ -f "$log_file" ] && [ -r "$log_file" ]; then
grep -i "$pattern" "$log_file" 2>/dev/null | while read -r line; do
echo "[$pattern] $log_file: $line"
done
fi
}
{
echo "=== Error Log Analysis ==="
echo "Search directory: $LOG_DIR"
echo "Analysis date: $(date)"
echo "Patterns searched: ${SEARCH_PATTERNS[*]}"
echo ""
# Find all log files
LOG_FILES=$(find "$LOG_DIR" -type f \( -name "*.log" -o -name "*.log.*" \) 2>/dev/null)
if [ -z "$LOG_FILES" ]; then
echo "No log files found in $LOG_DIR"
exit 1
fi
echo "Found $(echo "$LOG_FILES" | wc -l) log files"
echo ""
# Search each pattern in each log file
for pattern in "${SEARCH_PATTERNS[@]}"; do
echo "=== Searching for: $pattern ==="
echo ""
for log_file in $LOG_FILES; do
find_errors "$log_file" "$pattern"
done
echo ""
done
# Summary by log file
echo "=== Error Count by Log File ==="
for log_file in $LOG_FILES; do
if [ -f "$log_file" ] && [ -r "$log_file" ]; then
ERROR_COUNT=0
for pattern in "${SEARCH_PATTERNS[@]}"; do
COUNT=$(grep -ic "$pattern" "$log_file" 2>/dev/null || echo 0)
ERROR_COUNT=$((ERROR_COUNT + COUNT))
done
if [ $ERROR_COUNT -gt 0 ]; then
echo "$log_file: $ERROR_COUNT errors found"
fi
fi
done
echo ""
# Recent errors (last 100 lines of each log)
echo "=== Recent Errors (Last 100 lines) ==="
for log_file in $LOG_FILES; do
if [ -f "$log_file" ] && [ -r "$log_file" ]; then
RECENT_ERRORS=$(tail -100 "$log_file" 2>/dev/null | grep -iE "$(IFS='|'; echo "${SEARCH_PATTERNS[*]}")" | wc -l)
if [ $RECENT_ERRORS -gt 0 ]; then
echo ""
echo "--- $log_file (last 100 lines) ---"
tail -100 "$log_file" 2>/dev/null | grep -iE "$(IFS='|'; echo "${SEARCH_PATTERNS[*]}")"
fi
fi
done
} | tee "$OUTPUT_FILE"
echo ""
echo "Error analysis complete. Results saved to: $OUTPUT_FILE"
Quick error search commands:
# Search for errors in a single log
grep -i error /var/log/syslog
# Search multiple patterns
grep -iE "error|fatal|critical" /var/log/app.log
# Search with context (lines before/after)
grep -i error -A 5 -B 5 /var/log/app.log
# Count errors
grep -ic error /var/log/app.log
# Find errors in last hour
tail -1000 /var/log/app.log | grep -i error
# Search all log files in directory
grep -r "error" /var/log/