在 Debian 系统中,日志转储(Log Rotation)通常通过 logrotate 工具来完成。下面从原理、配置方式、常见示例、调试方法几个方面说明如何配置。
/etc/logrotate.conf/etc/logrotate.d/cron 或 systemd timer 定期触发(通常是每天)dpkg -l logrotate
查看定时任务:
ls -l /etc/cron.daily/logrotate
或(systemd 系统):
systemctl status logrotate.timer
示例(默认 Debian 通常已配置好):
weekly
rotate 4
create
compress
delaycompress
notifempty
include /etc/logrotate.d
含义:
| 参数 | 说明 |
|---|---|
| weekly | 每周轮转 |
| rotate 4 | 保留 4 个旧日志 |
| create | 轮转后新建日志文件 |
| compress | 压缩旧日志 |
| delaycompress | 延迟一次压缩 |
| notifempty | 空日志不轮转 |
| include | 加载应用配置 |
假设日志路径为 /var/log/myapp.log
创建配置文件:
sudo nano /etc/logrotate.d/myapp
内容示例:
/var/log/myapp.log {
daily
rotate 7
size 50M
missingok
notifempty
compress
delaycompress
create 0640 www-data www-data
postrotate
systemctl reload myapp > /dev/null 2>&1 || true
endscript
}
| 参数 | 说明 |
|---|---|
| daily | 每天轮转 |
| rotate 7 | 保留 7 份 |
| size 50M | 超过 50M 即轮转 |
| missingok | 日志不存在也不报错 |
| notifempty | 空文件不轮转 |
| compress | gzip 压缩 |
| create | 新建日志文件并设置权限 |
| postrotate | 轮转后执行命令 |
Debian 默认已有:
/etc/logrotate.d/rsyslog
示例内容:
/var/log/syslog
/var/log/auth.log
{
rotate 7
daily
missingok
notifempty
delaycompress
compress
postrotate
/usr/lib/rsyslog/rsyslog-rotate 2>/dev/null || true
endscript
}
logrotate -d /etc/logrotate.conf
-d表示 debug(不会真正执行)
logrotate -vf /etc/logrotate.conf
检查:
cat /var/lib/logrotate/status
确认:
确保:
create 参数设置正确✅ Debian 日志转储的标准方案是 logrotate
✅ 推荐为每个服务单独配置 /etc/logrotate.d/xxx
✅ 使用 logrotate -d 调试,避免误删日志
如果你愿意,我可以:
只要告诉我你的使用场景即可。