[DevOps] 4. 로그 파일 분석 (스크립트)

GisangLee·2025년 7월 9일
0

devops

목록 보기
4/11

웹서버 Pod를 만들었는데, 어떤 Source IP로 많이 들어오는지, 얼마나 들어오는지, 응답은 잘 하는지 궁금해졌다.

주요 명령어

| awk

  • (Aho + Weinberger + Kemighan)
  • awk의 기본 기능은 텍스트 형태로 되어 있는 입력 데이터를 행과 단어 별로 처리해 출력하는 것
동작 예시명령어
파일의 전체 내용 출력awk '{ print }' [FILE]
필드 값 출력awk '{ print $1}' [FILE]
필드 값에 임의 문자열을 같이 출력awk '{ print "STR"$1, "STR"$2 }' [FILE]

스크립트

#!/bin/bash

# =============== 🎨 스타일 정의 ================
bold=$(tput bold)
normal=$(tput sgr0)
green="\033[1;32m"
red="\033[1;31m"
yellow="\033[1;33m"
blue="\033[1;34m"
cyan="\033[1;36m"
white="\033[1;37m"
reset="\033[0m"

# =============== 📂 로그 경로 ================
LOG_FILE="/var/log/nginx/access.log"
if [ ! -f "$LOG_FILE" ]; then
  echo -e "${red}❌ 로그 파일이 존재하지 않습니다: $LOG_FILE${reset}"
  exit 1
fi

echo
echo -e "${blue}${bold}📊 NGINX ACCESS LOG REPORT${reset}"
echo -e "${white}🗂️   File     :${reset} $LOG_FILE"
echo -e "${white}📅 Generated :${reset} $(date '+%Y-%m-%d %H:%M:%S')"
echo "────────────────────────────────────────────────────"

# =============== 1️⃣ IP별 요청 수 ====================
echo -e "\n${cyan}🔹 TOP 10 ACCESS IPs${reset}"
printf "%-20s %s\n" "IP Address" "Count"
awk '{print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10 | awk '{printf "%-20s %s\n", $2, $1}'

# =============== 2️⃣ 시간대별 요청 수 (Hour 기준) ===
echo -e "\n${cyan}⏰ REQUESTS BY HOUR${reset}"
printf "%-10s %s\n" "Hour" "Count"
awk -F: '{gsub("\\[",""); print $2":00"}' "$LOG_FILE" | sort | uniq -c | sort -k2 | awk '{printf "%-10s %s\n", $2, $1}'

# =============== 3️⃣ HTTP 상태 코드 분포 ============
echo -e "\n${cyan}📶 HTTP STATUS CODES${reset}"
printf "%-10s %s\n" "Status" "Count"
awk '{print $9}' "$LOG_FILE" | grep -E '^[0-9]{3}$' | sort | uniq -c | sort -nr | awk '{printf "%-10s %s\n", $2, $1}'

# =============== 4️⃣ 가장 많이 요청된 URI ============
echo -e "\n${cyan}📌 TOP 10 REQUESTED URIs${reset}"
printf "%-40s %s\n" "URI Path" "Count"
awk '$6 ~ /GET|POST/ {print $7}' "$LOG_FILE" | sort | uniq -c | sort -nr | head -10 | awk '{printf "%-40s %s\n", $2, $1}'

# =============== 5️⃣ HTTP 메서드 분포 =================
echo -e "\n${cyan}🔠 HTTP METHOD COUNT${reset}"
printf "%-10s %s\n" "Method" "Count"
awk '{gsub(/"/, "", $6); print $6}' "$LOG_FILE" | sort | uniq -c | sort -nr | awk '{printf "%-10s %s\n", $2, $1}'

# =============== ✅ 완료 ====================
echo -e "\n${green}✅ 로그 분석 완료${reset}\n"
profile
포폴 및 이력서 : https://upbeat-suede-20b.notion.site/2265782662ce8071aeb7f67163e63467?source=copy_link

0개의 댓글