在Linux環境下,使用Swagger實現API的實時監控與報警可以通過以下步驟進行:
首先,確保你的項目中已經集成了Swagger。如果還沒有集成,可以使用以下命令安裝Swagger:
npm install swagger-ui-express --save
在你的Express應用中配置Swagger:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
為了實現實時監控,可以使用一些工具來監控API的性能和健康狀況。以下是一些常用的工具:
Prometheus是一個開源的監控系統和時間序列數據庫,Grafana是一個開源的分析和監控平臺。
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64
編輯prometheus.yml
文件,添加你的應用作為目標:
scrape_configs:
- job_name: 'node_exporter'
static_configs:
- targets: ['localhost:9100']
- job_name: 'myapp'
static_configs:
- targets: ['localhost:3000']
./prometheus --config.file=prometheus.yml
sudo apt-get install -y grafana
sudo systemctl start grafana-server
訪問http://localhost:3000
,使用默認用戶名和密碼(admin/admin)登錄,然后添加Prometheus作為數據源,并創建儀表盤來監控你的API。
ELK Stack(Elasticsearch, Logstash, Kibana)是一個流行的日志管理和分析平臺。
wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.10.0-linux-x86_64.tar.gz
tar xvfz elasticsearch-7.10.0-linux-x86_64.tar.gz
cd elasticsearch-7.10.0
./bin/elasticsearch
wget https://artifacts.elastic.co/downloads/logstash/logstash-7.10.0-linux-x86_64.tar.gz
tar xvfz logstash-7.10.0-linux-x86_64.tar.gz
cd logstash-7.10.0
編輯logstash.conf
文件,添加你的應用日志輸入和Elasticsearch輸出:
input {
file {
path => "/path/to/your/logs/*.log"
start_position => "beginning"
}
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "myapp-logs-%{+YYYY.MM.dd}"
}
}
./bin/logstash -f logstash.conf
sudo apt-get install -y kibana
sudo systemctl start kibana
訪問http://localhost:5601
,使用默認用戶名和密碼(kibana/kibana)登錄,然后配置Elasticsearch索引模式并創建儀表盤來監控你的API日志。
在Prometheus和Grafana中,你可以設置報警規則。例如,在Grafana中,你可以創建一個報警規則來監控API的響應時間:
groups:
- name: example
rules:
- alert: HighResponseTime
expr: rate(http_request_duration_seconds_sum[5m]) / rate(http_request_duration_seconds_count[5m]) > 1
for: 1m
labels:
severity: page
annotations:
summary: "High response time on {{ $labels.instance }}"
description: "{{ $labels.instance }} has a mean response time above 1 second (current value: {{ $value }}s)"
通過以上步驟,你可以在Linux環境下使用Swagger實現API的實時監控與報警。