监控Swagger API可以帮助您了解API的使用情况、性能指标和潜在问题。以下是几种在Linux环境中监控Swagger API的有效方法:
# 安装Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-*
# 配置prometheus.yml添加API监控目标
scrape_configs:
- job_name: 'swagger-api'
metrics_path: '/actuator/prometheus' # Spring Boot Actuator端点
static_configs:
- targets: ['your-api-host:8080']
# 启动Prometheus
./prometheus --config.file=prometheus.yml
# 安装Grafana
sudo apt-get install -y adduser libfontconfig1
wget https://dl.grafana.com/oss/release/grafana_8.1.5_amd64.deb
sudo dpkg -i grafana_8.1.5_amd64.deb
# 启动Grafana
sudo systemctl start grafana-server
# 示例Logstash配置
input {
http {
port => 8080
codec => "json"
}
}
filter {
grok {
match => { "message" => "%{TIMESTAMP_ISO8601:timestamp} %{LOGLEVEL:level} %{GREEDYDATA:message}" }
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "swagger-api-logs-%{+YYYY.MM.dd}"
}
}
如果您的API已经集成了Swagger UI,可以通过以下方式增强监控:
# Spring Boot配置示例
management:
endpoints:
web:
exposure:
include: "*"
metrics:
tags:
application: ${spring.application.name}
# 安装Kong
sudo apt-get update
sudo apt-get install -y kong
# 配置Kong
kong config init
kong start
#!/bin/bash
# 监控API响应时间和状态码
API_URL="http://localhost:8080/api/v1/users"
THRESHOLD_MS=500
while true; do
response=$(curl -o /dev/null -s -w "%{http_code} %{time_total}\n" "$API_URL")
status_code=$(echo $response | awk '{print $1}')
response_time=$(echo $response | awk '{print $2}')
response_time_ms=$(echo "$response_time * 1000" | bc)
if [ "$status_code" -ne 200 ]; then
echo "$(date) - ERROR: Status code $status_code" >> api_monitor.log
fi
if (( $(echo "$response_time_ms > $THRESHOLD_MS" | bc -l) )); then
echo "$(date) - WARNING: Slow response $response_time_ms ms" >> api_monitor.log
fi
sleep 5
done
# 安装OpenTelemetry Collector
wget https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.36.0/otelcol-contrib_0.36.0_linux_amd64.tar.gz
tar xvfz otelcol-contrib_*.tar.gz
通过以上方法,您可以全面监控Swagger API的性能、可用性和使用情况,确保API服务的稳定运行。