优化 Apache 日志以减少磁盘占用的实用方案
一 核心策略
二 快速落地步骤
/var/log/httpd/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 root adm
}
/var/log/apache2/*.log {
daily
missingok
rotate 7
compress
delaycompress
notifempty
create 640 root adm
}
ErrorLog "|/usr/sbin/rotatelogs -l /var/log/httpd/error_%Y%m%d.log 86400"
CustomLog "|/usr/sbin/rotatelogs -l /var/log/httpd/access_%Y%m%d.log 86400" combined
ErrorLog "|/usr/sbin/rotatelogs /var/log/httpd/errorlog.%Y-%m-%d-%H_%M_%S 5M"
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/accesslog.%Y-%m-%d-%H_%M_%S 5M" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog /var/log/httpd/access_log common
SetEnvIf User-Agent "BadBot" dont_log=1
CustomLog logs/access_log common env=!dont_log
以上做法能在不影响关键业务日志的前提下,减少无用访问日志的写入量。三 进阶与架构优化
四 配置示例汇总
/var/log/httpd/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 root adm
}
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog /var/log/httpd/access_log common
SetEnvIf User-Agent "BadBot" dont_log=1
CustomLog logs/access_log common env=!dont_log
LogLevel warn
ErrorLog "|/usr/sbin/rotatelogs -l /var/log/httpd/error_%Y%m%d.log 86400"
CustomLog "|/usr/sbin/rotatelogs -l /var/log/httpd/access_%Y%m%d.log 86400" combined
或ErrorLog "|/usr/sbin/rotatelogs /var/log/httpd/errorlog.%Y-%m-%d-%H_%M_%S 5M"
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/accesslog.%Y-%m-%d-%H_%M_%S 5M" combined
修改配置后,务必先执行 apachectl configtest 校验,再重启服务使生效。