Nginx日志是重要的运维数据,但不当配置可能导致磁盘空间快速耗尽。以下是几种有效的优化方法:
使用logrotate
工具自动分割和压缩旧日志:
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
对于生产环境,可以适当降低日志级别:
http {
error_log /var/log/nginx/error.log warn; # 只记录警告及以上级别
}
精简日志格式,移除不必要字段:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
只记录特定请求:
map $status $loggable {
~^[23] 0; # 不记录2xx和3xx响应
default 1;
}
access_log /var/log/nginx/access.log combined if=$loggable;
减少磁盘I/O操作:
access_log /var/log/nginx/access.log combined buffer=32k flush=5m;
对于静态资源可以关闭访问日志:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
access_log off;
}
对于高流量网站,可以将临时日志写入tmpfs:
mount -t tmpfs -o size=100m tmpfs /var/log/nginx/tmp
对于极高流量网站,可以只记录部分请求:
split_clients "$remote_addr$remote_port" $sample {
10% 1; # 记录10%的请求
* 0;
}
access_log /var/log/nginx/access.log combined if=$sample;
du -sh /var/log/nginx/
nginx -s reload
这些方法可以单独或组合使用,根据您的具体业务需求和服务器资源情况进行调整。