保存为monitor.sh

./monitor.sh access.log


#!/bin/bash

# Script to monitor and highlight IP, request path, and status code in a log file

# Function to highlight IP, request path, and status code
highlight_log() {
    sed -e "s/\(\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\)/\o033[1;31m\1\o033[0m/g" \
        -e "s/\(\"[A-Z]*\s\)\(.*\)\"/\1\o033[1;34m\2\o033[0m\"/g" \
        -e "s/\s[0-9]\{3\}\s/ \o033[1;32m&\o033[0m /g"
}

# Check if an argument is provided
if [ $# -ne 1 ]; then
    echo "Usage: $0 <logfile>"
    exit 1
fi

logfile="$1"

# Check if the logfile exists and is readable
if [ ! -f "$logfile" ]; then
    echo "Error: Logfile '$logfile' not found."
    exit 1
fi

# Temporary file (optional, can be removed if not needed)
tempfile=$(mktemp)

# Initial highlighting of existing log (last 20 lines)
tail -n 20 "$logfile" | highlight_log

# Monitor the log file for changes
tail -n 0 -f "$logfile" | while read line; do
    echo "$line" | highlight_log
done

# Clean up temporary file if any (optional)
rm -f "$tempfile"


点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部