温馨提示×

debian日志怎样轮转

小樊
37
2026-10-24 16:03:13
栏目: 智能运维

在 Debian 里,“日志轮转”通常是由 logrotate 工具来完成的。下面从「原理 → 配置 → 常用操作 → 示例」给你讲清楚。


一、Debian 日志轮转的基本原理

  • 核心工具:logrotate
  • 定时触发:通过 cron / systemd timer
    • /etc/cron.daily/logrotate
    • 或 logrotate.timer(systemd 系统)
  • 配置文件位置:
    • 主配置:/etc/logrotate.conf
    • 子配置目录:/etc/logrotate.d/

二、logrotate 的工作方式

每天(或按配置周期):

  1. 检查日志大小 / 时间
  2. 满足条件就:
    • 重命名日志(如 xxx.log → xxx.log.1)
    • 压缩旧日志(可选)
    • 创建新日志文件
    • 可选:发送信号给服务(如 nginx、rsyslog)

三、查看和手动执行

1️⃣ 查看 logrotate 状态

cat /var/lib/logrotate/status

2️⃣ 手动测试(不实际轮转)

logrotate -d /etc/logrotate.conf

3️⃣ 强制立即轮转

logrotate -f /etc/logrotate.conf

四、主配置文件示例(/etc/logrotate.conf)

weekly
su root syslog
rotate 4
compress
delaycompress
missingok
notifempty
create 0640 syslog adm
include /etc/logrotate.d

含义:

  • weekly:每周轮转
  • rotate 4:保留 4 份
  • compress:压缩旧日志
  • create:新建日志文件

五、为某个服务配置轮转(示例)

示例:自定义日志 /var/log/myapp.log

创建文件:

/etc/logrotate.d/myapp

内容:

/var/log/myapp.log {
    daily
    rotate 7
    compress
    missingok
    notifempty
    create 0640 www-data www-data
    postrotate
        systemctl reload myapp > /dev/null 2>&1 || true
    endscript
}

六、常见服务日志轮转位置

服务 配置文件
nginx /etc/logrotate.d/nginx
apache /etc/logrotate.d/apache2
rsyslog /etc/logrotate.d/rsyslog
apt /etc/logrotate.d/apt

七、常见问题排查

日志没轮转?

  • 检查 cron 是否运行:
    systemctl status cron
    
  • 查看 logrotate 错误:
    journalctl -u logrotate
    

日志变大但不压缩?

  • 确认 compress 是否启用
  • 注意 delaycompress 会延迟一轮

八、总结一句话

Debian 日志轮转 = logrotate + /etc/logrotate.d + cron/systemd

如果你有:

  • 特定服务(nginx / docker / 自定义程序)
  • 或想按「大小 / 时间 / 保留天数」定制

可以告诉我,我帮你写完整配置。

0 踩