温馨提示×

如何设置centos apache日志

小樊
35
2026-10-23 12:35:19
栏目: 智能运维

在 CentOS 上配置 Apache(通常是 httpd)的日志,主要涉及错误日志(error log)和访问日志(access log)的设置。下面从基础配置 → 常见自定义 → 日志切割 → 排错逐步说明。


一、Apache 日志配置文件位置

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_log

二、基础日志设置(httpd.conf)

1. 错误日志

ErrorLog logs/error_log
LogLevel warn

常见 LogLevel:

  • error(默认推荐)
  • warn
  • info
  • debug(排错用,生产环境不建议)

2. 访问日志

LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog logs/access_log common

常用格式:

  • common
  • combined(含 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 本身不支持自动按天建文件,可用:

方法 1:cron + mv(简单)

0 0 * * * mv /var/log/httpd/access_log /var/log/httpd/access_$(date +%F).log

方法 2:使用 rotatelogs(官方推荐)

CustomLog "|/usr/sbin/rotatelogs /var/log/httpd/access_%Y%m%d.log 86400" combined

六、常见排错

1. 日志不生成

ls -l /var/log/httpd/
getenforce   # 如果是 Enforcing

SELinux 修复:

restorecon -Rv /var/log/httpd

2. 权限问题

chown -R apache:apache /var/log/httpd

3. 配置生效

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

如果你需要:

  • ✅ 按虚拟主机分离日志
  • ✅ 只记录特定 IP / URL
  • ✅ 接入 ELK / 日志分析

可以告诉我你的使用场景,我可以给你更具体的配置。

0 踩