要从日志文件中快速提取Top 5接口访问次数,可以使用以下步骤:
awk
, sort
, uniq
, head
等)假设日志文件的格式如下:
2023-10-01 12:00:01 GET /api/v1/users 200
2023-10-01 12:00:02 POST /api/v1/login 200
2023-10-01 12:00:03 GET /api/v1/users 200
2023-10-01 12:00:04 GET /api/v1/products 200
2023-10-01 12:00:05 POST /api/v1/login 200
...
awk
提取日志中的接口路径(假设接口路径在第4列)。sort
和 uniq -c
统计每个接口的访问次数。sort -nr
按访问次数降序排序,并使用 head -n 5
提取前5个。awk '{print $4}' access.log | sort | uniq -c | sort -nr | head -n 5
如果你更喜欢使用Python,可以使用以下脚本:
from collections import defaultdict
# 读取日志文件
log_file = 'access.log'
api_counts = defaultdict(int)
with open(log_file, 'r') as file:
for line in file:
# 假设接口路径在第4列
parts = line.split()
if len(parts) >= 4:
api = parts[3]
api_counts[api] += 1
# 按访问次数排序并提取Top 5
top_5_apis = sorted(api_counts.items(), key=lambda x: x[1], reverse=True)[:5]
for api, count in top_5_apis:
print(f"{api}: {count}次")
grep
和 cut
组合如果你只需要简单的提取和统计,可以使用 grep
和 cut
组合:
grep -oP '(?<=GET|POST|PUT|DELETE) /[^ ]+' access.log | sort | uniq -c | sort -nr | head -n 5
Logstash
或 ELK
栈如果你有大量的日志数据,并且需要更复杂的分析,可以考虑使用 Logstash
或 ELK
(Elasticsearch, Logstash, Kibana)栈来处理日志数据,并通过Kibana进行可视化分析。
Pandas
(适用于数据分析)如果你已经熟悉 Pandas
,可以使用它来处理日志文件:
import pandas as pd
# 读取日志文件
log_file = 'access.log'
df = pd.read_csv(log_file, sep=' ', header=None, usecols=[3], names=['API'])
# 统计每个API的访问次数
api_counts = df['API'].value_counts()
# 提取Top 5
top_5_apis = api_counts.head(5)
print(top_5_apis)
awk
, sort
, uniq
)是最快速和高效的选择。Pandas
是更好的选择。ELK
栈或其他日志分析工具。根据你的需求和日志文件的规模,选择合适的方法来提取Top 5接口访问次数。