Swagger (OpenAPI) 是一个强大的API文档和测试工具,结合Linux环境可以实现高效的API日志分析。以下是完整的实现方案:
# 安装Swagger相关工具
npm install -g swagger-cli
# 安装日志分析工具
sudo apt-get install jq # JSON处理工具
sudo apt-get install awk # 文本处理工具
确保你的API项目已经集成了Swagger,并能生成OpenAPI规范文件(通常是swagger.json或openapi.json)。
log_format api_log '[$time_local] $remote_addr "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'rt=$request_time uct="$upstream_connect_time" '
'uht="$upstream_header_time" urt="$upstream_response_time"';
access_log /var/log/nginx/api_access.log api_log;
在应用代码中记录更详细的API调用信息,包括: - 请求时间 - 端点路径 - HTTP方法 - 响应状态码 - 响应时间 - 请求参数 - 用户标识(如适用)
# filebeat.yml 配置示例
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/nginx/api_access.log
- /var/log/your-app/api.log
output.elasticsearch:
hosts: ["localhost:9200"]
# logstash.conf 配置示例
filter {
grok {
match => { "message" => '\[%{TIMESTAMP_ISO8601:timestamp}\] %{IP:client_ip} "%{WORD:method} %{URIPATH:api_path} HTTP/%{NUMBER:http_version}" %{NUMBER:status} %{NUMBER:bytes_sent}' }
}
date {
match => ["timestamp", "ISO8601"]
target => "@timestamp"
}
mutate {
add_field => { "api_endpoint" => "%{method} %{api_path}" }
}
}
# 从Swagger文档提取所有API端点
jq '.paths | keys[]' swagger.json > endpoints.txt
#!/bin/bash
# 分析API响应时间
analyze_response_times() {
log_file=$1
awk '
BEGIN {
print "API Endpoint\tAverage Response Time\tMax Response Time\tMin Response Time\tRequest Count"
}
{
# 假设日志格式为: [timestamp] method path status response_time
endpoint = $2 " " $3;
resp_time = $5;
sum[endpoint] += resp_time;
count[endpoint]++;
if (max[endpoint] == "" || resp_time > max[endpoint]) {
max[endpoint] = resp_time;
}
if (min[endpoint] == "" || resp_time < min[endpoint]) {
min[endpoint] = resp_time;
}
}
END {
for (endpoint in sum) {
avg = sum[endpoint] / count[endpoint];
printf "%s\t%.3f\t%.3f\t%.3f\t%d\n", endpoint, avg, max[endpoint], min[endpoint], count[endpoint]
}
}
' $log_file | sort -k2 -nr
}
# 分析错误率
analyze_error_rates() {
log_file=$1
awk '
BEGIN {
print "API Endpoint\tTotal Requests\tError Requests\tError Rate"
}
{
endpoint = $2 " " $3;
status = $4;
total[endpoint]++;
if (status >= 400) {
errors[endpoint]++;
}
}
END {
for (endpoint in total) {
error_rate = (errors[endpoint] / total[endpoint]) * 100;
printf "%s\t%d\t%d\t%.2f%%\n", endpoint, total[endpoint], errors[endpoint], error_rate
}
}
' $log_file | sort -k4 -nr
}
# 主程序
case "$1" in
response)
analyze_response_times "$2"
;;
errors)
analyze_error_rates "$2"
;;
*)
echo "Usage: $0 {response|errors} logfile"
exit 1
;;
esac
// 在Swagger UI中添加性能指标展示
SwaggerUI({
dom_id: '#swagger-ui',
url: "swagger.json",
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
function() {
return {
components: {
Operation: function(props) {
// 从日志分析结果获取该端点的性能数据
const operationId = props.operation.get('operationId');
const stats = getStatsFromLogs(operationId); // 自定义函数
return (
<div>
{props.operation.get('method')} {props.operation.get('path')}
{stats && (
<div className="performance-stats">
<span>Avg: {stats.avgTime}ms</span>
<span>Errors: {stats.errorRate}%</span>
</div>
)}
</div>
);
}
}
};
}
]
});
# prometheus配置示例
scrape_configs:
- job_name: 'api_metrics'
static_configs:
- targets: ['localhost:9091'] # 假设你的应用暴露/metrics端点
groups:
- name: api.rules
rules:
- alert: HighErrorRate
expr: sum(rate(http_requests_total{status=~"5.."}[5m])) by (path) / sum(rate(http_requests_total[5m])) by (path) > 0.05
for: 10m
labels:
severity: critical
annotations:
summary: "High error rate on {{ $labels.path }}"
description: "{{ $value }} of requests are failing on {{ $labels.path }}"
通过以上方案,你可以充分利用Swagger的API定义和Linux强大的日志处理能力,构建一个完整的API监控分析系统。