Nginx 日志过大是生产环境中很常见的问题,通常可以从 日志切割、日志级别控制、访问日志优化、磁盘与监控、必要时关闭或转发 这几个方面来处理。
Nginx 官方和大多数系统都依赖 logrotate
示例配置(/etc/logrotate.d/nginx):
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
说明:
daily:每天切割rotate 14:保留 14 天compress:压缩旧日志kill -USR1:让 Nginx 重新打开日志文件测试:
logrotate -d /etc/logrotate.d/nginx # 调试
logrotate -f /etc/logrotate.d/nginx # 强制执行
mv access.log access.log.$(date +%Y%m%d)
kill -USR1 $(cat /var/run/nginx.pid)
error_log /var/log/nginx/error.log warn;
级别从低到高:
debug < info < notice < warn < error < crit
默认格式可能记录过多字段:
log_format minimal '$remote_addr - $request_time $status';
access_log /var/log/nginx/access.log minimal;
静态资源可不记录:
location ~* \.(js|css|png|jpg|gif|ico)$ {
access_log off;
}
只记录非正常请求:
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/access.log combined if=$loggable;
find 清理:find /var/log/nginx -name "*.log.*" -mtime +14 -delete
适合多台服务器:
好处:
access_log off;
⚠️ 仅限排查或特殊场景
✅ logrotate 每天切割 + 压缩
✅ error_log 设为 warn
✅ 静态资源不记录 access_log
✅ 监控磁盘使用率
如果你愿意,可以告诉我:
我可以给你一套 可以直接用的配置。