温馨提示×

如何解析nginx日志内容

小樊
62
2026-07-19 00:20:10
栏目: 编程语言

Nginx 日志解析通常分为 理解日志格式选择解析方式实际解析示例 三部分。下面以最常见的 访问日志(access.log) 为主说明。


一、Nginx 日志格式说明

1️⃣ 默认日志格式

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 实时可视化分析

三、常见解析示例

✅ 1. 统计访问量最高的 IP

awk '{print $1}' access.log | sort | uniq -c | sort -nr | head

✅ 2. 统计访问最多的 URL

awk '{print $7}' access.log | sort | uniq -c | sort -nr | head

$7 对应 /index.html


✅ 3. 统计 4xx / 5xx 错误

awk '{if ($9 >= 400) print $0}' access.log

或:

awk '$9 ~ /^[45]/' access.log

✅ 4. 按小时统计访问量

awk '{print $4}' access.log | cut -d: -f1-2 | uniq -c

输出示例:

120 [10/Nov/2024:14
98  [10/Nov/2024:15

四、Python 解析示例(推荐)

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 实时分析(强烈推荐)

goaccess /var/log/nginx/access.log -o report.html --log-format=COMBINED

✅ 自动生成:

  • PV / UV
  • 状态码分布
  • 热门 URL
  • 访问来源
  • 时间分布

六、生产环境建议

✅ 自定义日志格式(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。


七、你可以继续问我

  • 如何解析你当前的 nginx 日志格式?
  • 如何统计某个接口 QPS?
  • 如何用 Python / Go 批量分析?
  • 如何接入 ELK / Prometheus?

如果你愿意,可以直接贴一段 你的 access.log 示例,我可以帮你精确解析。

0