在 Nginx 中,按天生成日志通常有两种主流做法:
✅ 按虚拟主机按天切割(推荐)
✅ 使用 logrotate 按天切割(最常用、最稳定)
下面分开说明,并给出可直接用的配置示例。
http {
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;
error_log /var/log/nginx/error.log;
}
⚠️ 不要在 Nginx 里按天命名日志文件,否则 reload 时可能丢日志。
创建或编辑:
vim /etc/logrotate.d/nginx
示例配置(✅ 按天):
/var/log/nginx/*.log {
daily
rotate 30
missingok
notifempty
compress
delaycompress
dateext
dateformat -%Y%m%d
sharedscripts
postrotate
[ -s /run/nginx.pid ] && kill -USR1 $(cat /run/nginx.pid)
endscript
}
| 参数 | 含义 |
|---|---|
daily |
每天切割 |
rotate 30 |
保留 30 天 |
dateext |
日期后缀 |
dateformat -%Y%m%d |
示例:access.log-20260121 |
postrotate |
通知 Nginx 重新打开日志 |
logrotate -d /etc/logrotate.d/nginx # 调试
logrotate -f /etc/logrotate.d/nginx # 强制执行
第二天可以看到:
/var/log/nginx/access.log-20260121.gz
/var/log/nginx/access.log
✅ 这是生产环境最安全、最标准的方式
http {
map $time_iso8601 $logdate {
'~^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})' $year$month$day;
default 'unknown';
}
access_log /var/log/nginx/access-$logdate.log main;
}
生成示例:
access-20260121.log
access-20260122.log
如果是 Docker:
access_log /dev/stdout;
error_log /dev/stderr;
由 Docker / 日志驱动按天处理。
| 场景 | 推荐方案 |
|---|---|
| 生产环境(物理机 / 云服务器) | ✅ logrotate |
| 临时调试 | Nginx 按天 |
| Docker / K8s | stdout + 日志驱动 |
如果你愿意,我可以:
你现在的 Nginx 是 物理机 / Docker / K8s 哪种环境?