Nginx 預設日誌格式可讀性好但難以計算。本文介紹用控制字符 ^A (Ctrl+V Ctrl+A) 分割字段的結構化日誌格式,並提供十餘個生產級 AWK 一鍵分析腳本。
log_format analytics '$remote_addr^A$http_x_forwarded_for^A$host^A$time_local^A$status^A'
'$request_time^A$request_length^A$bytes_sent^A$http_referer^A$request^A$http_user_agent';
access_log /data/logs/nginx-access.log analytics buffer=32k flush=5s;
buffer=32k flush=5s:緩衝 32KB 或 5 秒刷盤,平衡 IO 與實時性。
$request_length 請求體大小$bytes_sent 響應體大小$request_time 請求處理耗時(秒)$connection 連接序號$connection_requests 當前連接請求數| 分析目標 | 命令 |
|---|---|
| Top N 訪問 URL | awk -F $'\x01' '{print $10}' access.log | sort | uniq -c | sort -nr | head -20 |
| 5xx 錯誤請求詳情 | awk -F $'\x01' '$5 ~ /^5/ {print $0}' access.log |
| 5xx 錯誤計數 | awk -F $'\x01' '$5 ~ /^5/ {print $0}' access.log | wc -l |
| 某分鐘 5xx 數量 | awk -F $'\x01' '$5 ~ /^5/ {print $0}' access.log | grep '09:00' | wc -l |
| 慢請求 (>1s) 實時監控 | tail -f access.log | awk -F $'\x01' '$6 > 1 {print $0}' |
| 慢請求僅看 Host+URL | tail -f access.log | awk -F $'\x01' '$6 > 1 {print $3"|"$4}' |
| 502 錯誤高頻 URL | awk -F $'\x01' '$5==502 {print $11}' access.log | sort | uniq -c | sort -nr |
| 200 但空白頁 (body<100B) | awk -F $'\x01' '$5==200 && $8<100 {print $3"|"$4"|"$11"|"$6}' access.log |
| 實時流式查看(可讀) | tail -f access.log | tr $'\x01' '|' |
$upstream_response_time、$upstream_addr 進行上游服務 SLA 分析。結構化日誌 + 命令行工具 = 輕量級實時可觀測系統,零依賴、秒級部署。