解析 Nginx 日志通常分为三步:确定日志格式 → 理解字段含义 → 使用工具/脚本解析分析。下面系统说明一下。
Nginx 主要有两种日志:
在 nginx.conf 中通常能看到:
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
}
| 变量 | 含义 |
|---|---|
$remote_addr |
客户端 IP |
$remote_user |
认证用户(一般为 -) |
$time_local |
访问时间 |
$request |
请求行(方法 + URL + 协议) |
$status |
HTTP 状态码 |
$body_bytes_sent |
响应体大小 |
$http_referer |
来源页面 |
$http_user_agent |
User-Agent |
$request_time |
请求处理时间 |
$upstream_response_time |
后端响应时间 |
$host |
域名 |
192.168.1.10 - - [18/Aug/2025:10:32:15 +0800] "GET /api/user?id=1 HTTP/1.1" 200 432 "-" "Mozilla/5.0 Chrome/120"
逐段解析:
IP: 192.168.1.10
User: -
时间: 18/Aug/2025:10:32:15 +0800
请求: GET /api/user?id=1 HTTP/1.1
状态码: 200
响应大小: 432
Referer: -
UA: Mozilla/5.0 Chrome/120
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $9}' access.log | sort | uniq -c
yum install goaccess -y
goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED
支持:
import re
pattern = re.compile(
r'(?P<ip>[\d\.]+) .*? \[(?P<time>.*?)\] '
r'"(?P<method>\w+) (?P<url>.*?) HTTP/.*?" '
r'(?P<status>\d+) (?P<size>\d+)'
)
with open("access.log") as f:
for line in f:
m = pattern.match(line)
if m:
print(m.groupdict())
推荐架构:
Nginx → Filebeat → Elasticsearch → Kibana
或:
Nginx → Fluent Bit → ClickHouse → Grafana
适合:
示例:
2025/08/18 10:30:12 [error] 1234#1234: *5678 upstream timed out
字段说明:
常用命令:
grep error /var/log/nginx/error.log
| 场景 | 方法 |
|---|---|
| 找出攻击 IP | awk + sort |
| 慢请求 | $request_time |
| 404 页面 | status==404 |
| 热点接口 | URL 统计 |
| 爬虫识别 | User-Agent |
log_format,至少包含:$request_time $upstream_response_time
如果你愿意,我可以:
你现在是用在 排查问题、统计分析,还是监控系统?