Nginx 日志解析通常分为 理解日志格式、选择解析方式、实际解析示例 三部分。下面以最常见的 访问日志(access.log) 为主说明。
Nginx 默认使用 Combined Log Format:
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
对应日志示例:
127.0.0.1 - - [10/Nov/2024:14:32:10 +0800] "GET /index.html HTTP/1.1" 200 1024 "http://example.com/" "Mozilla/5.0"
各字段含义:
| 字段 | 含义 |
|---|---|
$remote_addr |
客户端 IP |
$remote_user |
认证用户(通常为 -) |
$time_local |
访问时间 |
$request |
请求方法和路径 |
$status |
HTTP 状态码 |
$body_bytes_sent |
返回字节数 |
$http_referer |
来源页面 |
$http_user_agent |
浏览器/客户端信息 |
| 方式 | 适用场景 |
|---|---|
awk / grep |
快速统计、简单分析 |
| Python / Go | 复杂解析、结构化处理 |
| ELK / Grafana Loki | 大规模日志分析 |
| GoAccess | 实时可视化分析 |
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
awk '{print $7}' access.log | sort | uniq -c | sort -nr | head
$7对应/index.html
awk '{if ($9 >= 400) print $0}' access.log
或:
awk '$9 ~ /^[45]/' access.log
awk '{print $4}' access.log | cut -d: -f1-2 | uniq -c
输出示例:
120 [10/Nov/2024:14
98 [10/Nov/2024:15
import re
pattern = re.compile(
r'(?P<ip>[\d.]+) - - \[(?P<time>[^\]]+)\] '
r'"(?P<method>\w+) (?P<url>[^ ]+) HTTP/[\d.]+" '
r'(?P<status>\d+) (?P<size>\d+) '
r'"(?P<referer>[^"]*)" "(?P<ua>[^"]*)"'
)
with open("access.log") as f:
for line in f:
m = pattern.match(line)
if m:
print(m.groupdict())
输出为结构化字典,方便后续分析或入库。
goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED
✅ 自动生成:
✅ 自定义日志格式(JSON):
log_format json escape=json
'{'
'"ip":"$remote_addr",'
'"time":"$time_iso8601",'
'"method":"$request_method",'
'"url":"$request_uri",'
'"status":$status,'
'"ua":"$http_user_agent"'
'}';
解析更简单,适合 ELK / Loki。
如果你愿意,可以直接贴一段 你的 access.log 示例,我可以帮你精确解析。