插件窝 干货文章 如何在Linux中监控Swagger API

如何在Linux中监控Swagger API

Prometheus 监控 API response 46    来源:    2025-05-08

在Linux中监控Swagger API的方法

监控Swagger API可以帮助您了解API的使用情况、性能指标和潜在问题。以下是几种在Linux环境中监控Swagger API的有效方法:

1. 使用Prometheus + Grafana监控

安装和配置

# 安装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

# 安装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

2. 使用ELK Stack (Elasticsearch, Logstash, Kibana)

配置API日志收集

# 示例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}"
  }
}

3. 使用Swagger UI内置监控

如果您的API已经集成了Swagger UI,可以通过以下方式增强监控:

# Spring Boot配置示例
management:
  endpoints:
    web:
      exposure:
        include: "*"
  metrics:
    tags:
      application: ${spring.application.name}

4. 使用专用API监控工具

安装和配置Kong或Apigee

# 安装Kong
sudo apt-get update
sudo apt-get install -y kong

# 配置Kong
kong config init
kong start

5. 自定义脚本监控

#!/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

6. 使用OpenTelemetry进行分布式追踪

# 安装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

最佳实践

  1. 指标收集:监控请求率、错误率、延迟和饱和度
  2. 告警设置:为关键指标设置适当的阈值
  3. 日志聚合:集中存储和分析API日志
  4. 追踪集成:实现分布式追踪以识别性能瓶颈
  5. 定期审查:定期检查监控配置和告警规则

通过以上方法,您可以全面监控Swagger API的性能、可用性和使用情况,确保API服务的稳定运行。