Nginx 日志太大是常见问题,一般可以从切割、压缩、清理、控制内容、异步写盘几个方向处理。下面按实用程度给你一套方案。
Nginx 官方推荐方式。
示例配置(/etc/logrotate.d/nginx):
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0640 nginx nginx
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
说明:
daily:每天切rotate 30:保留 30 天compress:压缩旧日志kill -USR1:让 Nginx 重新打开日志(不重启)测试:
logrotate -d /etc/logrotate.d/nginx # 模拟
logrotate -f /etc/logrotate.d/nginx # 强制执行
默认日志太详细,可自定义:
log_format main '$remote_addr - $request_time $status $request';
access_log /var/log/nginx/access.log main;
常见可去掉:
$http_user_agent$http_referer$upstream_response_time(非必要)location ~* \.(jpg|png|css|js|gif|ico)$ {
access_log off;
}
静态请求通常占日志 70%+
location /health {
access_log off;
return 200;
}
error_log /var/log/nginx/error.log warn;
级别(从少到多):
crit < error < warn < notice < info < debug
find /var/log/nginx -name "*.log.*" -mtime +30 -delete
加进 crontab:
0 3 * * * find /var/log/nginx -name "*.log.*" -mtime +30 -delete
syslog 输出日志access_log syslog:server=127.0.0.1:514 main;
如果是被刷流量 / 攻击:
limit_req)✅ logrotate 每天切 + 压缩
✅ 静态资源不记日志
✅ access_log 精简格式
✅ error_log 用 warn
如果你愿意,可以告诉我:
我可以直接帮你写一份可用配置。