在 Ubuntu 上,Apache 的日志配置主要通过 Apache 的配置文件 来完成。下面按「常见需求」给你一个实用指南。
Ubuntu 下 Apache(通常是 apache2)默认日志在:
/var/log/apache2/
常见文件:
access.log:访问日志error.log:错误日志other_vhosts_access.log:虚拟主机访问日志(如启用)Apache 日志相关的主要指令有:
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
combined 是日志格式名,常用格式有:
commoncombined(最常用)编辑主配置文件:
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
查看配置:
cat /etc/logrotate.d/apache2
可修改:
LogFormat "%h %t \"%r\" %>s %b" myformat
CustomLog ${APACHE_LOG_DIR}/access.log myformat
ls -ld /var/log/apache2
sudo systemctl reload apache2
CustomLog /dev/null combined
如果你有具体需求(比如 按天分文件、记录真实 IP、Docker 环境、HTTPS 日志),可以告诉我,我给你更针对性的配置。