#!/bin/bash # ============================================================ # Log Analyzer # Usage: ./log_analyzer.sh # Example: ./log_analyzer.sh logs/server.log # Log line format: DATE TIME LEVEL MESSAGE # e.g. 2026-11-01 08:10:03 ERROR Disk space low on /home # ============================================================ # ---------- 1) Settings (variables) ---------- REPORT_DIR="reports" LOG_FILE="$1" # ---------- 2) Check the input argument ---------- if [ $# -ne 1 ]; then echo "Usage: $0 " echo "Example: $0 logs/server.log" exit 1 fi if [ ! -f "$LOG_FILE" ]; then echo "Error: file '$LOG_FILE' not found." exit 2 fi if [ ! -s "$LOG_FILE" ]; then echo "Error: file '$LOG_FILE' is empty." exit 3 fi # ---------- 3) Functions ---------- # Count lines that have a given level (INFO / WARNING / ERROR) count_level() { local level="$1" grep -c " $level " "$LOG_FILE" } # Show a short summary of the log file show_summary() { local total=$(wc -l < "$LOG_FILE") echo "------ Summary of $LOG_FILE ------" echo "Total lines : $total" echo "INFO : $(count_level INFO)" echo "WARNING : $(count_level WARNING)" echo "ERROR : $(count_level ERROR)" } # Show only ERROR lines show_errors() { echo "------ ERROR lines ------" grep " ERROR " "$LOG_FILE" } # Search for a word that the user types search_keyword() { read -p "Enter a word to search: " keyword if [ -z "$keyword" ]; then echo "Error: you did not enter any word." return fi echo "------ Lines containing '$keyword' ------" if ! grep -i -- "$keyword" "$LOG_FILE"; then echo "No result found for '$keyword'." fi } # Show the 3 most repeated error messages top_errors() { echo "------ Top 3 repeated errors ------" grep " ERROR " "$LOG_FILE" | cut -d' ' -f4- | sort | uniq -c | sort -nr | head -3 } # Save summary + top errors into a report file save_report() { mkdir -p "$REPORT_DIR" local report_file="$REPORT_DIR/report_$(date +%Y-%m-%d).txt" echo "Report created at: $(date '+%Y-%m-%d %H:%M:%S')" > "$report_file" show_summary >> "$report_file" top_errors >> "$report_file" echo "Report saved to: $report_file" } # ---------- 4) Main menu (loop) ---------- while true; do echo echo "========= Log Analyzer =========" echo "1) Show summary" echo "2) Show ERROR lines" echo "3) Search a word" echo "4) Top 3 repeated errors" echo "5) Save report" echo "0) Exit" read -p "Your choice: " choice case "$choice" in 1) show_summary ;; 2) show_errors ;; 3) search_keyword ;; 4) top_errors ;; 5) save_report ;; 0) echo "Goodbye!"; exit 0 ;; *) echo "Invalid choice. Please enter a number from 0 to 5." ;; esac done