温馨提示×

linux nginx日志如何分析

小樊
44
2026-09-20 21:52:29
栏目: 智能运维

在 Linux 下分析 Nginx 日志,通常分为 日志位置确认 → 日志格式理解 → 常用分析命令 → 可视化/工具 几个步骤。下面系统地讲一下。


一、Nginx 日志在哪里

默认路径一般在:

/var/log/nginx/access.log   # 访问日志
/var/log/nginx/error.log    # 错误日志

如果找不到,可以查配置:

nginx -T | grep -E 'access_log|error_log'

二、Nginx 日志格式

1. 默认 access.log 格式(combined)

$remote_addr - $remote_user [$time_local] "$request" 
$status $body_bytes_sent "$http_referer" 
"$http_user_agent"

示例:

192.168.1.10 - - [10/Oct/2024:14:22:01 +0800] "GET /index.html HTTP/1.1" 200 2326 "https://example.com/" "Mozilla/5.0"

2. 常见字段含义

  • remote_addr:客户端 IP
  • time_local:访问时间
  • request:请求方法 + URL + 协议
  • status:HTTP 状态码
  • body_bytes_sent:返回字节数
  • http_user_agent:客户端类型

三、日常命令行分析(最常用)

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

3. 统计 HTTP 状态码分布

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

4. 查看 404 / 500 错误

grep -E ' 404 | 500 ' access.log

5. 按时间段查看日志

awk '$4 >= "[10/Oct/2024:14:00:00" && $4 <= "[10/Oct/2024:15:00:00"' access.log

6. 统计 PV / UV

# PV
wc -l access.log

# UV
awk '{print $1}' access.log | sort -u | wc -l

四、错误日志分析

查看最近错误

tail -n 100 error.log

常见错误类型

  • connect() failed:后端服务异常
  • upstream timed out:代理超时
  • Permission denied:权限问题
  • No such file or directory:路径错误

五、进阶分析工具(推荐)

1. GoAccess(实时可视化)

goaccess access.log -o report.html --log-format=COMBINED

2. ELK / Grafana + Loki

适合:

  • 多台服务器
  • 长期日志分析
  • 告警

3. awk + sed 脚本化

适合自动化统计脚本。


六、日志切割(很重要)

防止日志过大:

# 使用 logrotate
cat /etc/logrotate.d/nginx

示例:

/var/log/nginx/*.log {
    daily
    rotate 14
    compress
    missingok
    notifempty
    sharedscripts
    postrotate
        systemctl reload nginx
    endscript
}

七、典型分析场景

场景 方法
被刷流量 统计 IP
接口慢 分析响应时间(需自定义日志)
爬虫 统计 User-Agent
异常报错 error.log + status
安全防护 fail2ban + 日志

如果你有 具体日志样例想分析某类问题(如慢请求、攻击、502),可以直接发出来,我可以帮你写具体命令。

0