在 Debian 上“切割 Apache 日志”通常指 log rotation(日志轮转/切割),防止 access.log / error.log 无限变大。Debian 下最常见、推荐的做法是使用 logrotate。下面按场景说明。
Debian 安装 Apache 后,通常会自动生成:
/etc/logrotate.d/apache2
cat /etc/logrotate.d/apache2
典型内容类似:
/var/log/apache2/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
systemctl reload apache2 > /dev/null 2>&1 || true
endscript
}
daily / weekly / monthly:切割频率rotate N:保留 N 个旧日志compress:压缩旧日志(.gz)size 100M:超过大小才切notifempty:空日志不切postrotate:切后让 Apache 重新打开日志logrotate -d /etc/logrotate.d/apache2 # 模拟
logrotate -f /etc/logrotate.d/apache2 # 强制执行
修改 /etc/logrotate.d/apache2:
/var/log/apache2/*.log {
size 100M
missingok
rotate 10
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
systemctl reload apache2
endscript
}
适合按时间切割,例如每小时一个文件。
CustomLog "|/usr/bin/rotatelogs /var/log/apache2/access_%Y%m%d%H.log 3600" combined
ErrorLog "|/usr/bin/rotatelogs /var/log/apache2/error_%Y%m%d%H.log 3600"
systemctl restart apache2
优点:
缺点:
必须让 Apache 重新打开日志
reload apache2权限问题
ls -l /var/log/apache2
通常属主:root:adm
确认 cron 在运行
systemctl status cron
| 场景 | 推荐方式 |
|---|---|
| Debian 标准环境 | logrotate |
| 按大小切割 | logrotate + size |
| 按小时/天精确切割 | rotatelogs |
| 多实例/容器 | rotatelogs 或自定义脚本 |
如果你愿意,可以告诉我:
我可以给你一份可直接用的配置。