nginx 日志很大的原因通常可以归结为访问量大、日志配置不合理、未做切割或未限制大小。下面从常见原因和优化建议两方面说明。
error_log 设置为 info 或 debugerror_log logs/error.log info; # 太详细
$request_body$http_user_agent$http_referer$upstream_response_timedu -sh /var/log/nginx/*
wc -l access.log
awk '{print $1}' access.log | sort | uniq -c | sort -nr | head
使用 logrotate(推荐)
vim /etc/logrotate.d/nginx
示例:
/var/log/nginx/*.log {
daily
rotate 7
missingok
notifempty
compress
delaycompress
sharedscripts
postrotate
nginx -s reload
endscript
}
error_log logs/error.log warn;
级别建议:
warn 或 errorinfo / debug只记录必要字段:
log_format main '$remote_addr - $request - $status';
access_log logs/access.log main;
避免记录:
location ~* \.(js|css|png|jpg|gif|ico|svg)$ {
access_log off;
}
location /health {
access_log off;
}
access_log logs/access.log main buffer=32k flush=5m;
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
limit_req zone=one burst=20 nodelay;
nginx 日志大,90% 的原因是:没做日志切割 + 记录了太多无用请求。
如果你愿意,可以把:
nginx.confaccess_log 示例贴出来我可以帮你针对性精简配置。