在 Debian 上轮转 Nginx 日志通常有两种做法:
logrotate(推荐)下面分别说明。
Debian 默认安装了 logrotate,并且 Nginx 包通常会自带配置文件。
cat /etc/logrotate.d/nginx
典型内容类似:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
prerotate
if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
run-parts /etc/logrotate.d/httpd-prerotate; \
fi \
endscript
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}
daily:每天轮转weekly:每周rotate 14:保留 14 个旧日志compress:压缩旧日志notifempty:日志为空不轮转postrotate:让 Nginx 重新打开日志文件logrotate -d /etc/logrotate.d/nginx # 测试(不实际执行)
logrotate -f /etc/logrotate.d/nginx # 强制轮转
例如:保留 30 天、压缩、每天轮转
编辑:
sudo nano /etc/logrotate.d/nginx
修改为:
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl kill -s USR1 nginx.service
endscript
}
USR1信号会让 Nginx 重新打开日志文件(相当于nginx -s reopen)
Nginx 主进程收到 USR1 信号后会:
无需重启服务,不影响线上访问。
如果你不用 logrotate:
mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +%Y%m%d)
kill -USR1 $(cat /var/run/nginx.pid)
然后配合 cron 定时执行。
logrotate 是否运行:systemctl status logrotate/etc/cron.daily/logrotate确保日志目录权限:
ls -ld /var/log/nginx
如果你愿意,我可以: