linux

Linux中Swagger API的监控和日志如何设置

小樊
43
2025-07-31 22:57:09
栏目: 智能运维

在Linux中设置Swagger API的监控和日志,可以通过以下步骤进行:

Swagger API监控设置

  1. 安装Swagger
npm install -g swagger-jsdoc swagger-ui-express
  1. 配置Swagger
{
  "swagger": "2.0",
  "info": {
    "title": "My API",
    "version": "1.0.0"
  },
  "paths": {
    "/api/v1/items": {
      "get": {
        "summary": "Get items",
        "responses": {
          "200": {
            "description": "A list of items"
          }
        }
      }
    }
  }
}
  1. 集成Swagger到你的应用
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  1. 使用Swagger进行API性能监控
ab -n 100 -c 10 http://localhost:3000/api/v1/items
  1. 监控和日志分析
# 安装Prometheus和Grafana
# 配置Prometheus抓取Swagger的指标
  1. 优化Swagger性能

Swagger API日志设置

  1. 生成Swagger文档
  1. 配置API请求日志
log_format api_log '$remote_addr - $remote_user [$time_local] '
                      '"$request" $status $body_bytes_sent '
                      '"$http_referer" "$http_user_agent" '
                      '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;
  1. 日志收集与处理
filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/nginx/api_access.log
    - /var/log/your-app/api.log
output.elasticsearch:
  hosts: ["localhost:9200"]
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}" }
  }
}
  1. 结合Swagger进行日志分析
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 </bash>

通过以上步骤,你可以在Linux上成功设置Swagger API的监控和日志功能,从而提高API的可维护性和可用性。

0
看了该问题的人还看了