«

Nginx 日志分析技巧

时间:2026-10-8 07:18     作者:emer     分类: 无


Nginx 日志分析技巧

Nginx 日志是排查问题的重要工具,学会分析日志很重要。

1. 日志位置

默认日志路径:

# 访问日志
/var/log/nginx/access.log

# 错误日志
/var/log/nginx/error.log

2. 日志格式

默认日志格式:

log_format access '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent"';

3. 常用分析命令

1)查看访问量最多的IP:

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

2)查看访问最多的页面:

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

3)查看状态码分布:

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

4)查看404错误:

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

4. 排查常用

1)查看哪个IP访问频繁:

grep "127.0.0.1" access.log

2)查看某个时间段日志:

grep "08/Oct/2026:07" access.log

3)查看错误日志:

tail -f error.log

5. 日志切割

用 logrotate 自动切割:

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 30
    compress
    notifempty
    create 0640 nginx adm
    postrotate
        systemctl reload nginx
    endscript
}

6. 常用场景

总结

Nginx 日志分析要点:

做运维,看日志是基本功。

标签: Nginx 运维 日志 分析 排查