在 Ubuntu 上,Apache2 的日志配置主要通过主配置文件和虚拟主机(VirtualHost)配置来完成。下面按常见场景给你说明。
Apache2 默认有两种日志:
/var/log/apache2/access.log/var/log/apache2/error.log/etc/apache2/apache2.conf
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog ${APACHE_LOG_DIR}/access.log common
说明:
ErrorLog:错误日志路径LogLevel:日志级别(debug, info, notice, warn, error, crit)LogFormat:定义日志格式CustomLog:访问日志路径和格式/etc/apache2/sites-available/your-site.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>
combined 是 Apache 内置格式,包含:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" myformat
CustomLog ${APACHE_LOG_DIR}/access.log myformat
which rotatelogs
CustomLog "|/usr/bin/rotatelogs ${APACHE_LOG_DIR}/access_%Y%m%d.log 86400" combined
Ubuntu 默认使用 logrotate 管理 Apache 日志:
/etc/logrotate.d/apache2
通常无需修改,默认每周轮转并压缩。
sudo apache2ctl configtest
sudo systemctl restart apache2
# 实时查看访问日志
tail -f /var/log/apache2/access.log
# 实时查看错误日志
tail -f /var/log/apache2/error.log
如果你有具体需求(比如:只记录某个 IP、关闭日志、JSON 格式日志、HTTPS 站点),可以告诉我,我可以给你针对性配置。