温馨提示×

apache日志ubuntu如何配置

小樊
47
2026-10-06 12:47:41
栏目: 智能运维

在 Ubuntu 上配置 Apache 日志(访问日志和错误日志)通常涉及修改 Apache 的配置文件。下面从基础位置、配置方法、常见参数、按虚拟主机配置、日志轮转几个方面说明。


一、Apache 日志默认位置(Ubuntu)

Ubuntu 使用 apache2,日志默认在:

/var/log/apache2/

常见文件:

  • access.log:访问日志
  • error.log:错误日志
  • other_vhosts_access.log:其他虚拟主机访问日志

二、核心配置文件位置

/etc/apache2/

主要相关文件/目录:

  • /etc/apache2/apache2.conf:全局配置
  • /etc/apache2/sites-available/:虚拟主机配置
  • /etc/apache2/conf-available/:额外配置
  • /etc/apache2/envvars:环境变量(如日志权限)

三、配置访问日志(Access Log)

1. 基本指令

CustomLog ${APACHE_LOG_DIR}/access.log combined

combined 是常见日志格式,包含:

  • IP
  • 时间
  • 请求
  • 状态码
  • User-Agent
  • Referer

2. 常见日志格式

在 apache2.conf 中定义:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common

使用:

CustomLog ${APACHE_LOG_DIR}/access.log combined

四、配置错误日志(Error Log)

ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn

日志级别(从低到高)

debug < info < notice < warn < error < crit < alert < emerg

例如:

LogLevel error

五、按虚拟主机配置日志(推荐)

编辑虚拟主机:

sudo nano /etc/apache2/sites-available/example.conf

示例:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example

    ErrorLog ${APACHE_LOG_DIR}/example_error.log
    CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>

启用站点:

sudo a2ensite example.conf
sudo systemctl reload apache2

六、按条件记录日志(高级)

不记录静态文件

SetEnvIf Request_URI "\.(jpg|png|css|js)$" static
CustomLog ${APACHE_LOG_DIR}/access.log combined env=!static

七、日志轮转(Logrotate)

Ubuntu 默认已配置:

/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
}

手动测试:

sudo logrotate -d /etc/logrotate.d/apache2

八、检查与生效

sudo apache2ctl configtest
sudo systemctl restart apache2

九、常见问题

1. 日志不生成?

  • 检查目录权限
  • 查看 APACHE_LOG_DIR
  • 确认 CustomLog / ErrorLog 已配置

2. 日志太大?

  • 使用 logrotate
  • 过滤静态资源
  • 降低 LogLevel

如果你有具体需求(如:按天分割、JSON 日志、Docker、HTTPS 站点),可以告诉我,我给你针对性配置。

0 踩