温馨提示×

怎么在Linux监控Swagger

小樊
34
2026-07-10 14:05:08
栏目: 智能运维

在 Linux 上“监控 Swagger”通常有两种理解,我分别说明,你可以按需要选择。


一、监控 Swagger 接口是否可用 / 是否正常

(最常见需求:监控 Swagger 页面或接口是否在线)

1️⃣ 监控 Swagger UI 页面是否正常

Swagger UI 通常是:

http://<ip>:<port>/swagger-ui.html
http://<ip>:<port>/swagger-ui/index.html

使用 curl 监控

curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/swagger-ui.html
  • 返回 200:正常
  • 200:异常

可写成脚本:

#!/bin/bash
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/swagger-ui.html)
if [ "$STATUS" != "200" ]; then
  echo "Swagger UI is down"
fi

2️⃣ 监控 Swagger API 文档接口(JSON)

Swagger 实际的接口文档通常是:

/v2/api-docs        (Swagger 2)
/v3/api-docs        (OpenAPI 3)
curl http://localhost:8080/v3/api-docs | jq .info.title

✅ 能返回 JSON 说明服务正常


二、监控 Swagger 接口 调用情况 / 性能 / 异常

(偏生产环境)

1️⃣ 通过应用日志监控

如果 Swagger 只是接口文档,真正要监控的是 接口本身

查看接口访问日志:

tail -f /var/log/your-app/app.log | grep "/api/"

常见监控指标:

  • 请求数
  • 响应时间
  • 5xx 错误
  • 慢请求

2️⃣ 使用 Prometheus + Grafana(推荐)

如果服务暴露了 metrics(Spring Boot 为例):

开启 actuator

management:
  endpoints:
    web:
      exposure:
        include: "*"

访问:

http://localhost:8080/actuator/prometheus

Prometheus 可监控:

  • QPS
  • 接口耗时
  • 错误率

三、监控 Swagger 是否被非法访问(安全监控)

(防止接口文档泄露)

1️⃣ 检查 Swagger 是否可被外网访问

curl -I http://<公网IP>/swagger-ui.html

2️⃣ Nginx 限制访问

location /swagger-ui.html {
    allow 127.0.0.1;
    deny all;
}

四、自动化监控(生产推荐)

工具 用途
cron + curl 定时检查
Prometheus 指标监控
Grafana 可视化
Zabbix 传统监控
ELK 日志分析

示例 cron:

*/5 * * * * curl -f http://localhost:8080/swagger-ui.html || echo "Swagger down"

五、我可以进一步帮你

你可以告诉我:

  1. 用的是 Spring Boot / Node / Python / Go
  2. 想监控的是 可用性 / 性能 / 接口调用量 / 安全
  3. 是否有 Prometheus / Nginx / Docker

我可以直接给你一套 可复制的监控方案

0