Skip to content

日志分析

分析日志可以获取有用的信息,用于优化和监控。

基本分析

统计访问量

bash
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr

统计状态码

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

统计访问URL

bash
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr

高级分析

统计访问量前10的IP

bash
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

统计访问量前10的URL

bash
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10

统计错误日志

bash
grep "error" /var/log/nginx/error.log | wc -l

统计响应时间

bash
awk '{print $NF}' /var/log/nginx/access.log | sort -n | tail -10

实时监控

实时查看访问日志

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

实时查看错误日志

bash
tail -f /var/log/nginx/error.log

实时统计访问量

bash
watch -n 1 'awk "{print \$1}" /var/log/nginx/access.log | sort | uniq -c | sort -nr | head -10'

使用工具分析

使用GoAccess

安装GoAccess

bash
sudo apt install goaccess

分析日志

bash
goaccess /var/log/nginx/access.log -c

使用AWStats

安装AWStats

bash
sudo apt install awstats

配置AWStats

bash
sudo vi /etc/awstats/awstats.conf

生成报告

bash
sudo /usr/lib/cgi-bin/awstats.pl -config=example.com -update

完整示例

分析脚本

bash
#!/bin/bash
# 日志分析脚本

LOG_FILE="/var/log/nginx/access.log"

echo "访问量前10的IP:"
awk '{print $1}' $LOG_FILE | sort | uniq -c | sort -nr | head -10

echo -e "\n访问量前10的URL:"
awk '{print $7}' $LOG_FILE | sort | uniq -c | sort -nr | head -10

echo -e "\n状态码统计:"
awk '{print $9}' $LOG_FILE | sort | uniq -c | sort -nr

echo -e "\n错误日志统计:"
grep "error" /var/log/nginx/error.log | wc -l

常见问题

日志文件过大

原因: 日志记录过多

解决: 使用日志轮转

bash
sudo vi /etc/logrotate.d/nginx

分析速度慢

原因: 日志文件过大

解决: 分析部分日志

bash
tail -10000 /var/log/nginx/access.log | awk '{print $1}' | sort | uniq -c | sort -nr

总结

日志分析的关键点:

  • 基本分析:统计访问量、状态码、URL
  • 高级分析:统计前10、错误日志、响应时间
  • 实时监控:实时查看日志
  • 使用工具:GoAccess、AWStats
  • 分析脚本:自动化分析

合理分析日志,获取有用信息,用于优化和监控。