在 Ubuntu 上,Apache 的日志通常位于 /var/log/apache2/ 目录,常见日志文件包括:
access.log:访问日志error.log:错误日志other_vhosts_access.log:虚拟主机访问日志(如有)下面从 日志格式、手动解析、命令行工具、可视化/解析工具 几个方面说明。
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 | 客户端信息 |
[Wed Oct 10 13:55:02.123456 2024] [core:error] [pid 1234] [client 192.168.1.10:55555] script not found
tail -f /var/log/apache2/access.log
tail -f /var/log/apache2/error.log
awk '{print $1}' /var/log/apache2/access.log | sort | uniq -c | sort -nr | head
awk '{print $9}' /var/log/apache2/access.log | sort | uniq -c | sort -nr
grep ' 404 ' /var/log/apache2/access.log
grep '10/Oct/2024:13:5' /var/log/apache2/access.log
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
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
如果你有 具体需求(如:统计某个接口、分析攻击、导出 CSV、ELK 解析),可以告诉我,我可以给你更针对性的方案。