温馨提示×

怎样分析linuxnginx日志

小樊
37
2026-09-17 19:19:05
栏目: 智能运维

分析 Linux 下 Nginx 日志,通常从日志位置、日志格式、常用分析命令、可视化工具几个方面入手。下面给你一套实用指南。


一、先找到 Nginx 日志

1. 常见日志路径

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

2. 确认配置位置

nginx -t

输出示例:

configuration file /etc/nginx/nginx.conf test is successful

查看日志路径:

grep -R "access_log" /etc/nginx/
grep -R "error_log" /etc/nginx/

二、理解 Nginx 日志格式

默认 access_log 格式(combined)

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

示例:

192.168.1.10 - - [12/Apr/2024:10:22:31 +0800] 
"GET /index.html HTTP/1.1" 200 1024 
"https://example.com/" "Mozilla/5.0"

常见字段含义

  • remote_addr:客户端 IP
  • time_local:访问时间
  • request:请求方法和路径
  • status:HTTP 状态码
  • body_bytes_sent:返回字节数
  • user_agent:客户端类型

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

1. 查看实时日志

tail -f /var/log/nginx/access.log

2. 统计访问最多的 IP

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

3. 统计 HTTP 状态码分布

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

4. 查看 404 / 500 错误

awk '$9 == 404' access.log
awk '$9 >= 500' access.log

5. 统计热门 URL

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

6. 按小时统计访问量

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

四、错误日志分析

查看错误日志

tail -n 100 /var/log/nginx/error.log

常见错误

  • permission denied → 文件权限问题
  • upstream timed out → 后端服务慢
  • no live upstreams → 后端全部不可用

五、进阶分析方式

1. 使用 GoAccess(实时可视化)

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

2. 使用 ELK / Grafana + Loki

适合生产环境、多台服务器

  • Filebeat 收集日志
  • Elasticsearch 存储
  • Kibana 可视化

六、建议的分析思路

  1. 先看病(错误日志)
  2. 再看量(访问量、IP、URL)
  3. 最后看质量(状态码、响应时间)
  4. 异常 IP / 爬虫 / 攻击优先处理

如果你愿意,可以:

  • 发一段真实日志样例
  • 说明你是排错 / 安全 / 性能分析

我可以直接帮你写针对性分析命令或脚本

0