在Linux中設置Swagger API的監控和日志,可以通過以下步驟進行:
npm install -g swagger-jsdoc swagger-ui-express
swagger.json
或swagger.yaml
。這個文件定義了你的API規范,包括路徑、方法、參數、響應等。{
"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"
}
}
}
}
}
}
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');
});
http://localhost:3000/api-docs
來查看和測試你的API文檔。為了進行性能監控,你可以使用一些性能測試工具,如ApacheBench(ab)、Siege或sysbench。ab -n 100 -c 10 http://localhost:3000/api/v1/items
# 安裝Prometheus和Grafana
# 配置Prometheus抓取Swagger的指標
swagger.json
或openapi.json
)。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;
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}" }
}
}
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的可維護性和可用性。