温馨提示×

apache日志格式怎样设置

小樊
40
2026-09-12 11:26:36
栏目: 编程语言

Apache 的日志格式主要通过 LogFormatCustomLog(或 ErrorLog)指令来设置,通常在 httpd.conf 或虚拟主机配置文件中完成。

下面按常见场景说明。


一、基础概念

1. LogFormat

定义“日志格式模板”,给一个名字(如 combinedcommon)。

2. CustomLog

指定“把哪种格式写到哪个文件”。

3. ErrorLog

错误日志一般不用自定义格式,直接指定文件即可。


二、常用内置格式

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 请求处理时间(秒)

四、自定义日志格式示例

示例 1:记录 IP + 时间 + URL + 状态码 + 耗时

LogFormat "%h %t \"%r\" %>s %D" mylog
CustomLog logs/access_log mylog

示例 2:JSON 格式(方便 ELK / 日志分析)

LogFormat "{ \
  \"time\":\"%t\", \
  \"client\":\"%h\", \
  \"request\":\"%r\", \
  \"status\":%>s, \
  \"bytes\":%b, \
  \"ua\":\"%{User-Agent}i\" \
}" jsonlog

CustomLog logs/access_json.log jsonlog

示例 3:虚拟主机中单独设置

<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

六、小贴士

  • 不确定格式是否生效:先访问页面,再看日志文件
  • 高并发场景建议减少字段,降低 IO
  • 若用日志分析系统(如 Filebeat),推荐 JSON 格式

如果你有 具体想记录的字段使用场景(如安全审计 / 性能分析),我可以帮你定制一条 LogFormat。

0