温馨提示×

apache日志格式ubuntu如何设

小樊
46
2026-09-06 16:13:58
栏目: 智能运维

在 Ubuntu 上,Apache 的日志格式主要通过 LogFormat 和 CustomLog 指令来设置,配置文件一般在:

  • Ubuntu/Debian 系统:/etc/apache2/apache2.conf
  • 或虚拟主机配置:/etc/apache2/sites-available/*.conf

一、查看默认日志格式

Apache 默认已定义了一些格式,例如在 apache2.conf 中常见:

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:包含 Referer 和 User-Agent(最常用)

二、使用已有格式(推荐)

在虚拟主机中直接使用:

CustomLog ${APACHE_LOG_DIR}/access.log combined

三、自定义日志格式(示例)

1️⃣ 添加自定义格式

在 apache2.conf 或虚拟主机配置中加入:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %D" mylog

说明:

  • %D:请求处理时间(微秒)
  • %T:请求处理时间(秒)
  • %{X-Forwarded-For}i:代理真实 IP

2️⃣ 应用自定义格式

CustomLog ${APACHE_LOG_DIR}/access.log mylog

四、常见格式变量说明

变量 含义
%h 客户端 IP
%u 认证用户
%t 时间
%r 请求行
%>s 状态码
%b 响应大小
%{Referer}i 来源页
%{User-Agent}i 浏览器
%D 处理时间(μs)

五、修改后生效

sudo apache2ctl configtest
sudo systemctl restart apache2

六、示例:记录真实 IP(反代场景)

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

如果你有 具体想记录的字段(比如 JSON 格式、时间格式、CDN 场景),可以告诉我,我可以直接给你一份完整配置。

0 踩