BASH

Search Log Files for Patterns with Context

Use this bash script to efficiently search multiple log files for specific patterns and display matching lines along with surrounding context for better debugging and analysis.

#!/bin/bash

# Configuration
DEFAULT_LOG_DIR="/var/log" # Default directory to search
CONTEXT_LINES=5 # Number of lines before and after the match
SEARCH_OPTIONS="-E -i -C $CONTEXT_LINES" # grep options (Extended regex, case-insensitive, Context)

# Function to display usage
usage() {
  echo "Usage: $0 <pattern> [log_directory]"
  echo "  <pattern>: The regular expression to search for."
  echo "  [log_directory]: Optional. The directory to search logs in. Defaults to $DEFAULT_LOG_DIR."
  exit 1
}

# Check for required argument
if [ -z "$1" ]; then
  usage
fi

SEARCH_PATTERN="$1"
LOG_DIR=${2:-$DEFAULT_LOG_DIR} # Use provided directory or default

if [ ! -d "$LOG_DIR" ]; then
  echo "Error: Log directory '$LOG_DIR' not found."
  exit 1
fi

echo "Searching for pattern '$SEARCH_PATTERN' in '*.log*' files under '$LOG_DIR' (with $CONTEXT_LINES lines of context)..."

# Find all .log files (including compressed .log.gz, .log.1, etc.) and grep them
# -print0 and xargs -0 handle filenames with spaces correctly
find "$LOG_DIR" -type f \( -name "*.log" -o -name "*.log.*" -o -name "*.gz" \) -print0 | xargs -0 zgrep $SEARCH_OPTIONS "$SEARCH_PATTERN" 2>/dev/null

# Check grep exit status
if [ $? -eq 0 ]; then
  echo "
Search complete: Matches found."
elif [ $? -eq 1 ]; then
  echo "
Search complete: No matches found for '$SEARCH_PATTERN'."
else
  echo "
Search completed with errors (e.g., inaccessible files)."
  exit 1
fi
How it works: This powerful script streamlines log file analysis by searching for a specified pattern across all `.log` files (and common variations like `.log.gz`, `.log.1`) within a given directory. It leverages `grep`'s extended regex and case-insensitive options, crucially displaying several lines of context around each match. This contextual information is invaluable for quickly understanding the surrounding events of an error or specific log entry, significantly aiding in debugging and troubleshooting.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs