温馨提示×

ubuntu apache日志怎么解析

小樊
41
2026-10-27 01:19:14
栏目: 智能运维

在 Ubuntu 上,Apache 的日志通常位于 /var/log/apache2/ 目录,常见日志文件包括:

  • access.log:访问日志
  • error.log:错误日志
  • other_vhosts_access.log:虚拟主机访问日志(如有)

下面从 日志格式、手动解析、命令行工具、可视化/解析工具 几个方面说明。


一、Apache 日志格式

1. 默认访问日志格式(combined)

192.168.1.10 - - [10/Oct/2024:13:55:01 +0000] "GET /index.html HTTP/1.1" 200 2326 "https://example.com" "Mozilla/5.0"

字段含义:

字段 说明
IP 客户端 IP
- 远程日志名(通常为 -)
- 认证用户
时间 请求时间
请求 方法 + URL + 协议
状态码 HTTP 状态码
大小 响应大小
Referer 来源页
User-Agent 客户端信息

2. 错误日志示例

[Wed Oct 10 13:55:02.123456 2024] [core:error] [pid 1234] [client 192.168.1.10:55555] script not found

二、基础命令行解析

1. 查看最新日志

tail -f /var/log/apache2/access.log
tail -f /var/log/apache2/error.log

2. 统计访问 IP 排行

awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -nr | head

3. 统计状态码

awk '{print $9}' /var/log/apache2/access.log | sort | uniq -c | sort -nr

4. 查看 404 请求

grep ' 404 ' /var/log/apache2/access.log

5. 按时间筛选

grep '10/Oct/2024:13:5' /var/log/apache2/access.log

三、使用 GoAccess(实时可视化)

安装

sudo apt update
sudo apt install goaccess

解析并查看

goaccess /var/log/apache2/access.log -o report.html --log-format=COMBINED

或终端实时:

goaccess /var/log/apache2/access.log --log-format=COMBINED

四、使用 awk / python 自定义解析(进阶)

Python 简单解析示例

import re

pattern = re.compile(
    r'(?P<ip>\S+) \S+ \S+ \[(?P<time>.*?)\] "(?P<req>.*?)" (?P<status>\d+) (?P<size>\S+)'
)

with open('/var/log/apache2/access.log') as f:
    for line in f:
        m = pattern.match(line)
        if m:
            print(m.groupdict())

五、日志切割与管理

Ubuntu 默认使用 logrotate:

/etc/logrotate.d/apache2

手动测试:

sudo logrotate -d /etc/logrotate.d/apache2

六、常见分析目标

  • 找出攻击 IP(大量 404 / 500)
  • 分析慢请求
  • 统计爬虫
  • 查看错误集中时间
  • 优化 SEO(404、301)

如果你有 具体需求(如:统计某个接口、分析攻击、导出 CSV、ELK 解析),可以告诉我,我可以给你更针对性的方案。

0 踩