在 CentOS 上配置 Apache(通常是 httpd)的日志,主要涉及错误日志(error log)和访问日志(access log)的设置。下面从基础配置 → 常见自定义 → 日志切割 → 排错逐步说明。
CentOS 中 Apache 一般使用 httpd:
/etc/httpd/conf/httpd.conf/etc/httpd/conf.d/*.conf/var/log/httpd/默认日志文件:
/var/log/httpd/access_log/var/log/httpd/error_logErrorLog logs/error_log
LogLevel warn
常见 LogLevel:
error(默认推荐)warninfodebug(排错用,生产环境不建议)LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog logs/access_log common
常用格式:
commoncombined(含 Referer 和 User-Agent)LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog logs/access_log combined
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html/example
ErrorLog /var/log/httpd/example_error.log
CustomLog /var/log/httpd/example_access.log combined
</VirtualHost>
CentOS 默认使用 logrotate
配置文件:
/etc/logrotate.d/httpd
示例(系统默认已存在):
/var/log/httpd/*log {
missingok
notifempty
sharedscripts
delaycompress
postrotate
/bin/systemctl reload httpd > /dev/null 2>/dev/null || true
endscript
}
手动测试:
logrotate -d /etc/logrotate.d/httpd # 测试
logrotate -f /etc/logrotate.d/httpd # 强制执行
Apache 本身不支持自动按天建文件,可用:
0 0 * * * mv /var/log/httpd/access_log /var/log/httpd/access_$(date +%F).log
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_%Y%m%d.log 86400" combined
ls -l /var/log/httpd/
getenforce # 如果是 Enforcing
SELinux 修复:
restorecon -Rv /var/log/httpd
chown -R apache:apache /var/log/httpd
httpd -t
systemctl restart httpd
ErrorLog /var/log/httpd/error.log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_%Y%m%d.log 86400" combined
如果你需要:
可以告诉我你的使用场景,我可以给你更具体的配置。