在 Ubuntu 上,Apache2 的日志配置主要通过主配置文件和虚拟主机(VirtualHost)配置来完成。下面从基础到常见用法给你讲清楚。
Ubuntu 中 Apache2 默认日志路径:
/var/log/apache2/
├── access.log # 访问日志
├── error.log # 错误日志
├── other_vhosts_access.log
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
combined 是日志格式名(见下文)
查看已有格式:
grep -R "LogFormat" /etc/apache2/
默认格式示例:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
常用格式:
commoncombined(最常用)编辑主配置文件:
sudo nano /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
编辑站点配置:
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
LogLevel warn
可选:
emergalertcriterrorwarn(默认)noticeinfodebug调试用:
LogLevel debug
CustomLog "|/usr/bin/rotatelogs ${APACHE_LOG_DIR}/access.%Y-%m-%d.log 86400" combined
每天一个日志文件
Ubuntu 默认已配置:
/etc/logrotate.d/apache2
可修改保留天数:
sudo nano /etc/logrotate.d/apache2
# 实时查看访问日志
tail -f /var/log/apache2/access.log
# 查看错误
tail -f /var/log/apache2/error.log
# 统计 404
grep " 404 " /var/log/apache2/access.log | wc -l
如果你愿意,我可以:
直接告诉我你的使用场景即可。