在 Ubuntu 上配置 Apache 日志(访问日志和错误日志)通常涉及修改 Apache 的配置文件。下面从基础位置、配置方法、常见参数、按虚拟主机配置、日志轮转几个方面说明。
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:环境变量(如日志权限)CustomLog ${APACHE_LOG_DIR}/access.log combined
combined 是常见日志格式,包含:
在 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
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
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
APACHE_LOG_DIRCustomLog / ErrorLog 已配置logrotateLogLevel如果你有具体需求(如:按天分割、JSON 日志、Docker、HTTPS 站点),可以告诉我,我给你针对性配置。