Apache 的日志格式主要通过 LogFormat 和 CustomLog(或 ErrorLog)指令来设置,通常在 httpd.conf 或虚拟主机配置文件中完成。
下面按常见场景说明。
定义“日志格式模板”,给一个名字(如 combined、common)。
指定“把哪种格式写到哪个文件”。
错误日志一般不用自定义格式,直接指定文件即可。
Apache 默认提供两种常用格式:
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
使用方式:
CustomLog logs/access_log combined
| 字段 | 含义 |
|---|---|
%h |
客户端 IP |
%l |
远程登录名(通常为 -) |
%u |
认证用户 |
%t |
时间 |
%r |
请求行(如 GET /index.html HTTP/1.1) |
%>s |
响应状态码 |
%b |
响应字节数 |
%{Referer}i |
来源页面 |
%{User-Agent}i |
浏览器标识 |
%D |
请求处理时间(微秒) |
%T |
请求处理时间(秒) |
LogFormat "%h %t \"%r\" %>s %D" mylog
CustomLog logs/access_log mylog
LogFormat "{ \
\"time\":\"%t\", \
\"client\":\"%h\", \
\"request\":\"%r\", \
\"status\":%>s, \
\"bytes\":%b, \
\"ua\":\"%{User-Agent}i\" \
}" jsonlog
CustomLog logs/access_json.log jsonlog
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html
LogFormat "%h %t \"%r\" %>s %b" vhostlog
CustomLog ${APACHE_LOG_DIR}/example_access.log vhostlog
ErrorLog ${APACHE_LOG_DIR}/example_error.log
</VirtualHost>
apachectl configtest
systemctl restart apache2 # 或 httpd
如果你有 具体想记录的字段 或 使用场景(如安全审计 / 性能分析),我可以帮你定制一条 LogFormat。