温馨提示×

Apache日志格式如何设置

小樊
40
2026-07-13 06:59:12
栏目: 编程语言

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

下面按常见场景说明。


一、Apache 日志格式的基本概念

Apache 主要有两种日志:

  • 访问日志(Access Log):记录客户端请求
  • 错误日志(Error Log):记录错误信息

你问的“日志格式”通常指 访问日志格式


二、查看默认日志格式

在 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)

三、常用日志格式说明

1️⃣ combined(最常用)

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 浏览器标识

2️⃣ common(简单)

LogFormat "%h %l %u %t \"%r\" %>s %b" common

四、如何设置日志格式(示例)

1️⃣ 全局设置(httpd.conf)

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog logs/access_log combined

2️⃣ 虚拟主机中设置(推荐)

<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>

五、自定义日志格式(常见需求)

1️⃣ 记录真实客户端 IP(经过 CDN / 代理)

LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %>s %b" proxy
CustomLog logs/access.log proxy

2️⃣ 记录请求耗时(性能分析)

LogFormat "%h %t \"%r\" %>s %b %D" timed
  • %D:请求耗时(微秒)

3️⃣ JSON 格式日志(方便 ELK / 日志分析)

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:错误日志

推荐

  • 普通站点:combined
  • 有 CDN / 代理:X-Forwarded-For
  • 日志分析系统:JSON 格式

如果你愿意,可以告诉我:

  • Apache 版本(2.2 / 2.4)
  • 是否使用 CDN / Nginx 反代
  • 是否用于 ELK / 日志分析

我可以帮你给出最合适的日志格式配置

0