Apache 的日志格式主要通过 LogFormat 和 CustomLog 指令来设置,通常在 httpd.conf 或 虚拟主机配置文件(如 vhost.conf) 中配置。
下面按常见场景说明。
Apache 主要有两种日志:
你问的“日志格式”通常指 访问日志格式。
在 Apache 配置中常见如下内容:
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
common:简单格式combined:常用格式(比 common 多 Referer 和 User-Agent)LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
含义:
| 字段 | 含义 |
|---|---|
%h |
客户端 IP |
%l |
远程登录名(通常 -) |
%u |
认证用户 |
%t |
时间 |
%r |
请求(方法 + URL + 协议) |
%>s |
HTTP 状态码 |
%b |
响应大小 |
%{Referer}i |
来源页面 |
%{User-Agent}i |
浏览器标识 |
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
<VirtualHost *:80>
ServerName www.example.com
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog logs/example_access.log combined
ErrorLog logs/example_error.log
</VirtualHost>
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b" proxy
CustomLog logs/access.log proxy
LogFormat "%h %t \"%r\" %>s %b %D" timed
%D:请求耗时(微秒)LogFormat "{ \"time\":\"%t\", \"client\":\"%h\", \"method\":\"%m\", \"url\":\"%U\", \"status\":\"%>s\", \"size\":\"%b\" }" json
CustomLog logs/access.log json
错误日志一般不能自定义格式,但可以设置级别:
ErrorLog logs/error.log
LogLevel warn
日志级别(从低到高):
debug → info → notice → warn → error → crit → alert → emerg
修改配置后:
apachectl configtest
systemctl restart httpd
# 或
apachectl restart
✅ 核心指令
LogFormat:定义日志格式CustomLog:指定日志文件和格式ErrorLog:错误日志✅ 推荐
combinedX-Forwarded-For如果你愿意,可以告诉我:
我可以帮你给出最合适的日志格式配置。