温馨提示×

ubuntu apache日志怎样配置

小樊
47
2026-09-15 17:48:26
栏目: 智能运维

在 Ubuntu 上,Apache 的日志配置主要通过 Apache 的配置文件 来完成。下面按「常见需求」给你一个实用指南。


一、Apache 日志文件位置(默认)

Ubuntu 下 Apache(通常是 apache2)默认日志在:

/var/log/apache2/

常见文件:

  • access.log:访问日志
  • error.log:错误日志
  • other_vhosts_access.log:虚拟主机访问日志(如启用)

二、核心日志配置指令

Apache 日志相关的主要指令有:

1. 错误日志

ErrorLog ${APACHE_LOG_DIR}/error.log

2. 访问日志

CustomLog ${APACHE_LOG_DIR}/access.log combined

combined 是日志格式名,常用格式有:

  • common
  • combined(最常用)
  • 自定义格式

三、全局配置(影响所有站点)

编辑主配置文件:

sudo nano /etc/apache2/apache2.conf

或(Ubuntu 推荐):

sudo nano /etc/apache2/conf-available/logging.conf
sudo a2enconf logging

示例:

ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog ${APACHE_LOG_DIR}/access.log combined

四、针对某个虚拟主机配置日志

编辑虚拟主机配置文件:

sudo nano /etc/apache2/sites-available/example.com.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.com
sudo systemctl reload apache2

五、日志级别(调试用)

LogLevel warn

可选级别(从少到多):

emerg alert crit error warn notice info debug

调试时可用:

LogLevel debug

六、按时间或大小切割日志(推荐)

1. 使用 logrotate(Ubuntu 默认已配置)

查看配置:

cat /etc/logrotate.d/apache2

可修改:

  • 每天 / 每周
  • 保留份数
  • 是否压缩

七、自定义日志格式(进阶)

LogFormat "%h %t \"%r\" %>s %b" myformat
CustomLog ${APACHE_LOG_DIR}/access.log myformat

八、常见问题

1. 日志不生成?

  • 检查目录权限:
ls -ld /var/log/apache2
  • 重新加载 Apache:
sudo systemctl reload apache2

2. 想禁用访问日志

CustomLog /dev/null combined

如果你有具体需求(比如 按天分文件、记录真实 IP、Docker 环境、HTTPS 日志),可以告诉我,我给你更针对性的配置。

0