下面以 Linux 下常见的 Apache2(如 Ubuntu/Debian) 为例,说明如何配置 Apache2 日志。
Apache2 主要有两类日志:
访问日志(Access Log)
记录每一次 HTTP 请求
默认路径(Ubuntu):
/var/log/apache2/access.log
错误日志(Error Log)
记录服务器运行错误、PHP 错误等
默认路径:
/var/log/apache2/error.log
/etc/apache2/apache2.conf
/etc/apache2/sites-available/
/etc/apache2/conf-enabled/
或
/etc/apache2/apache2.conf
在虚拟主机或全局配置中:
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
combined 是常用日志格式${APACHE_LOG_DIR} 通常是 /var/log/apache2LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
常见格式说明:
%h:客户端 IP%t:时间%r:请求行%>s:状态码%b:响应大小%{User-Agent}i:浏览器信息LogFormat "%h %t \"%r\" %>s %b %D" myformat
CustomLog ${APACHE_LOG_DIR}/access.log myformat
%D 表示请求处理时间(微秒)
示例:
<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
Ubuntu 默认已配置:
/etc/logrotate.d/apache2
可修改保留天数:
rotate 14
关闭访问日志:
CustomLog /dev/null combined
关闭错误日志(不建议):
ErrorLog /dev/null
查看错误:
sudo tail -f /var/log/apache2/error.log
配置修改后:
sudo apache2ctl configtest
sudo systemctl restart apache2
如果你需要:
可以告诉我你的具体场景。