API を運用しているみなさんは、「API が応答しなくなったのに気づかなかった」「エラーが多発していたのに後から気づいた」という経験はありませんか?私も最初は手動でログを確認していましたが流量が増えるにつれ追いきれなくなり、Prometheus と Alertmanager を導入しました。本記事では、完全初心者でもわかるように API 监控告警の構築方法を説明します。

API 监控告警とは?なぜ必要なのか

API 监控告警とは、API の動きを常にチェックして問題が起きそうなときに 미리警告해주는仕組みです。Prometheus は指标数据を収集するツール、Alertmanager はその数据を見て异常時に通知を送るツールです。この2つを組み合わせることで、まるで番人みたいに API を守り続けられます。

监控でできること

まずは Prometheus をインストールしよう

Prometheus は开源の监控系统です。下载安装の方法を説明します。

Step 1: Docker で 간단導入

初心者には Docker を使うのが最もかんたんです。以下のコマンドを実行してください。

# docker-compose.yml を作成
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
  prometheus:
    image: prom/prometheus:latest
    container_name: prometheus
    ports:
      - "9090:9090"
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
      - ./alerts.yml:/etc/prometheus/alerts.yml
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
      - '--web.enable-lifecycle'
    restart: unless-stopped

  alertmanager:
    image: prom/alertmanager:latest
    container_name: alertmanager
    ports:
      - "9093:9093"
    volumes:
      - ./alertmanager.yml:/etc/alertmanager/alertmanager.yml
    command:
      - '--config.file=/etc/alertmanager/alertmanager.yml'
    restart: unless-stopped
EOF

echo "docker-compose.yml を作成しました"

Step 2: Prometheus 設定ファイルを作成

prometheus.yml と alerts.yml を以下のように作成します。 api.holysheep.ai のエンドポイントを監視する例です。

# prometheus.yml - 監視対象の設定
global:
  scrape_interval: 15s
  evaluation_interval: 15s

alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - alertmanager:9093

rule_files:
  - "alerts.yml"

scrape_configs:
  - job_name: 'holysheep-api-monitor'
    static_configs:
      - targets: ['localhost:9091']
    metrics_path: '/metrics'
    scrape_interval: 10s

---

alerts.yml - 告警ルール定義

groups: - name: holysheep-api-alerts interval: 30s rules: # API 响应时间超过 2 秒的告警 - alert: APIHighLatency expr: api_request_duration_seconds > 2 for: 2m labels: severity: warning annotations: summary: "API 响应时间过长" description: "API 延迟 {{ $value }}s 超过阈值" # 错误率超过 5% 的告警 - alert: APIHighErrorRate expr: rate(api_errors_total[5m]) / rate(api_requests_total[5m]) > 0.05 for: 1m labels: severity: critical annotations: summary: "API 错误率过高" description: "错误率 {{ $value | humanizePercentage }}" # 速率限制接近的告警 - alert: RateLimitApproaching expr: rate(api_requests_total[1m]) > 0.8 * api_rate_limit for: 30s labels: severity: warning annotations: summary: "速率限制接近" description: "当前请求率 {{ $value }} 接近限制"

Step 3: Alertmanager 設定ファイルを作成

# alertmanager.yml - 通知先設定
global:
  resolve_timeout: 5m

route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 12h
  receiver: 'default-receiver'
  routes:
    - match:
        severity: critical
      receiver: 'critical-receiver'
      continue: true
    - match:
        severity: warning
      receiver: 'warning-receiver'

receivers:
  - name: 'default-receiver'
    email_configs:
      - to: '[email protected]'
        from: '[email protected]'
        smarthost: 'smtp.example.com:587'
        auth_username: 'alertmanager'
        auth_password: 'your-password'

  - name: 'critical-receiver'
    webhook_configs:
      - url: 'http://your-app:5000/webhook'
        send_resolved: true

  - name: 'warning-receiver'
    slack_configs:
      - api_url: 'https://hooks.slack.com/services/YOUR/WEBHOOK'
        channel: '#api-alerts'
        send_resolved: true

Step 4: Prometheus を起動

# コンテナを起動
docker-compose up -d

状态确认

docker-compose ps

Prometheus の UI を確認

ブラウザで http://localhost:9090 にアクセス

実践:HolySheep AI API の监控Exporterを作る

では、実際に HolySheep AI(https://api.holysheep.ai/v1)の API を监控する exporter を作成しましょう。HolySheep AI は 注册で無料クレジットがもらえ、レートが ¥1=$1(公式 ¥7.3=$1 比 85% 節約)という圧倒的なコストパフォーマンスが特徴です。

# holysheep_exporter.py
import requests
import time
from prometheus_client import Counter, Histogram, Gauge, start_http_server

Prometheus 指标定义

REQUEST_COUNT = Counter( 'holysheep_api_requests_total', 'Total API requests', ['endpoint', 'status'] ) REQUEST_LATENCY = Histogram( 'holysheep_api_request_duration_seconds', 'API request latency', ['endpoint'] ) ERROR_COUNT = Counter( 'holysheep_api_errors_total', 'Total API errors', ['error_type'] ) RATE_LIMIT_USAGE = Gauge( 'holysheep_api_rate_limit_usage', 'Rate limit usage percentage', ['endpoint'] ) API_KEY = "YOUR_HOLYSHEEP_API_KEY" # HolySheep AI の API キーを設定 BASE_URL = "https://api.holysheep.ai/v1" def check_api_health(): """API 健康状态检查""" endpoints = [ "/models", "/chat/completions" ] for endpoint in endpoints: start_time = time.time() try: if endpoint == "/models": response = requests.get( f"{BASE_URL}{endpoint}", headers={"Authorization": f"Bearer {API_KEY}"}, timeout=5 ) else: # 测试聊天端点(轻量请求) response = requests.post( f"{BASE_URL}{endpoint}", headers={ "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" }, json={ "model": "gpt-4.1", "messages": [{"role": "user", "content": "ping"}], "max_tokens": 5 }, timeout=5 ) latency = time.time() - start_time # 记录指标 REQUEST_COUNT.labels(endpoint=endpoint, status=response.status_code).inc() REQUEST_LATENCY.labels(endpoint=endpoint).observe(latency) # 检查速率限制响应头 if 'x-ratelimit-remaining' in response.headers: remaining = int(response.headers['x-ratelimit-remaining']) limit = int(response.headers.get('x-ratelimit-limit', 1000)) usage = (limit - remaining) / limit * 100 RATE_LIMIT_USAGE.labels(endpoint=endpoint).set(usage) print(f"✓ {endpoint}: {response.status_code} ({latency*1000:.2f}ms)") except requests.exceptions.Timeout: ERROR_COUNT.labels(error_type='timeout').inc() REQUEST_COUNT.labels(endpoint=endpoint, status='timeout').inc() print(f"✗ {endpoint}: Timeout") except requests.exceptions.RequestException as e: ERROR_COUNT.labels(error_type='network').inc() REQUEST_COUNT.labels(endpoint=endpoint, status='error').inc() print(f"✗ {endpoint}: {str(e)}") if __name__ == '__main__': # Prometheus 用端口启动 start_http_server(9091) print("Exporter 已启动,端口 9091") print(f"监控 HolySheep AI: {BASE_URL}") # 每 10 秒检查一次 while True: check_api_health() time.sleep(10)

私の实践经验では、<50ms のレイテンシを実現できる HolySheep AI は监控システムとの相性がとても良いです。延迟が少ないため、告警の误报(网络延迟导致的误报)が大幅に减りました。

监控ダッシュボードを Grafana で可视化

Prometheus のデータを見やすくするために Grafana を設定しましょう。

# grafana 用 docker-compose.yml を追加
cat >> docker-compose.yml << 'EOF'

  grafana:
    image: grafana/grafana:latest
    container_name: grafana
    ports:
      - "3000:3000"
    volumes:
      - ./grafana:/var/lib/grafana
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
    restart: unless-stopped
EOF

Grafana を再起動

docker-compose up -d grafana

Prometheus データソースを追加

ブラウザで http://localhost:3000 にアクセス

ユーザー: admin / パスワード: admin

[Configuration] > [Data Sources] > [Add data source]

Type: Prometheus

URL: http://prometheus:9090

[Save & Test]

おすすめ Grafana ダッシュボード設定

実践的な监控シナリオ 3選

シナリオ1: 每日報告の自動送信

每日の API 利用状況をまとめ、Wecom/Slack に自動送信する設定です。

# daily_report.py
import requests
import datetime
from prometheus_api_client import PrometheusConnect

prom = PrometheusConnect(url="http://localhost:9090")

def generate_daily_report():
    today = datetime.date.today()
    
    # 24时间のデータを取得
    queries = {
        '总请求数': 'sum(increase(holysheep_api_requests_total[24h]))',
        '平均延迟': 'avg(holysheep_api_request_duration_seconds[24h]) * 1000',
        'P95延迟': 'quantile(0.95, holysheep_api_request_duration_seconds[24h]) * 1000',
        '错误数': 'sum(increase(holysheep_api_errors_total[24h]))',
        '错误率': 'sum(increase(holysheep_api_errors_total[24h])) / sum(increase(holysheep_api_requests_total[24h])) * 100'
    }
    
    report = f"📊 HolySheep AI 每日报告 - {today}\n\n"
    
    for metric, query in queries.items():
        try:
            value = prom.custom_query(query)
            if value:
                val = float(value[0]['value'][1])
                if '率' in metric:
                    report += f"• {metric}: {val:.2f}%\n"
                elif '延迟' in metric:
                    report += f"• {metric}: {val:.2f}ms\n"
                else:
                    report += f"• {metric}: {val:.0f}\n"
        except Exception as e:
            report += f"• {metric}: 获取失败\n"
    
    # Slack に送信
    webhook_url = "https://hooks.slack.com/services/YOUR/WEBHOOK"
    requests.post(webhook_url, json={"text": report})
    
    print("日报已发送:", report)

if __name__ == '__main__':
    generate_daily_report()

シナリオ2: 紧急时的自动应急措施

критический 错误が起きたときに API を一時的に遮断し、代替えサービスに切り替え应急。

# emergency_handler.py
import requests
import smtplib
from email.mime.text import MIMEText

class EmergencyHandler:
    def __init__(self):
        self.fallback_url = "https://api.holysheep.ai/v1"  # HolySheep 备用
        self.primary_url = "https://api.holysheep.ai/v1"
        
    def handle_critical_alert(self, alert_data):
        """ критический 告警时的应急处理 """
        print(f"🚨 紧急告警: {alert_data['alertname']}")
        
        # 1. Slack 通知
        self.send_slack_notification(alert_data)
        
        # 2. メール送信
        self.send_email_alert(alert_data)
        
        # 3. API 流量切换
        self.switch_to_fallback()
        
        # 4. 问题记录
        self.log_incident(alert_data)
        
    def send_slack_notification(self, alert_data):
        webhook = "https://hooks.slack.com/services/YOUR/WEBHOOK"
        message = f"""
🚨 *紧急告警*
*Alert:* {alert_data['alertname']}
*Severity:* {alert_data.get('severity', 'unknown')}
*Time:* {alert_data.get('activeAt', 'N/A')}
*Details:* {alert_data.get('description', 'No description')}
        """
        requests.post(webhook, json={"text": message, "mrkdwn": True})
        
    def send_email_alert(self, alert_data):
        msg = MIMEText(f"紧急告警发生\n\n{alert_data}")
        msg['Subject'] = f"[紧急] {alert_data['alertname']}"
        msg['From'] = "[email protected]"
        msg['To'] = "[email protected]"
        
        with smtplib.SMTP('smtp.example.com', 587) as server:
            server.starttls()
            server.login('user', 'password')
            server.send_message(msg)
            
    def switch_to_fallback(self):
        """切换到备用 API"""
        print("切换 API 到备用服务...")
        # 这里可以实现实际的切换逻辑
        pass
        
    def log_incident(self, alert_data):
        """记录事故"""
        with open('incidents.log', 'a') as f:
            f.write(f"{datetime.datetime.now()}: {alert_data}\n")

シナリオ3: コスト最適化のアラート

HolySheep AI は GPT-4.1 $8/MTok、Claude Sonnet 4.5 $15/MTok、Gemini 2.5 Flash $2.50/MTok、DeepSeek V3.2 $0.42/MTok と 다양한モデルが选べますが、成本监控も重要です。

# cost_monitor.py
import requests
from prometheus_client import Counter, Gauge

コスト関連指标

TOKEN_USAGE = Counter( 'holysheep_token_usage_total', 'Total tokens used by model', ['model', 'type'] # type: prompt/completion ) COST_ESTIMATE = Gauge( 'holysheep_estimated_cost_usd', 'Estimated cost in USD', ['model'] ) MODEL_PRICES = { 'gpt-4.1': {'input': 8.0, 'output': 8.0}, # $8/MTok 'claude-sonnet-4.5': {'input': 15.0, 'output': 15.0}, # $15/MTok 'gemini-2.5-flash': {'input': 2.50, 'output': 2.50}, # $2.50/MTok 'deepseek-v3.2': {'input': 0.42, 'output': 0.42}, # $0.42/MTok } COST_THRESHOLD_DAILY = 100 # 每日成本上限 $100 def calculate_cost(usage_data): """コスト計算とアラート""" total_cost = 0 for model, tokens in usage_data.items(): if model in MODEL_PRICES: price = MODEL_PRICES[model] cost = (tokens['prompt'] * price['input'] + tokens['completion'] * price['output']) / 1_000_000 total_cost += cost COST_ESTIMATE.labels(model=model).set(cost) print(f"当前预估日成本: ${total_cost:.2f}") # コストが閾値を超えたら Alertmanager に通知 if total_cost > COST_THRESHOLD_DAILY: send_cost_alert(total_cost) def send_cost_alert(current_cost): """コスト超過アラート""" alertmanager_url = "http://localhost:9093/api/v1/alerts" alert = [{ "labels": { "alertname": "HighAPICost", "severity": "warning", "service": "holysheep-cost" }, "annotations": { "summary": f"API成本超限: ${current_cost:.2f}", "description": f"每日成本 ${current_cost:.2f} 超过阈值 ${COST_THRESHOLD_DAILY}" } }] requests.post(alertmanager_url, json=alert) print(f"⚠️ コストアラート送信: ${current_cost:.2f}")

よくあるエラーと対処法

エラー1: Prometheus がターゲットをスクレイプできない

错误訊息: server returned HTTP status 404: Not Found

原因: Exporter が起動していない、またはポートが間違っている場合に発生します。

# 排查步骤

1. Exporter の状态确认

docker-compose ps

2. Exporter 端口连通性测试

curl http://localhost:9091/metrics

3. 解决: Exporter を再启动

docker-compose restart holysheep-exporter

4. prometheus.yml の targets 确认

scrape_configs > targets: ['holysheep-exporter:9091'] のように服务名可以使用

エラー2: Alertmanager の通知が届かない

错误訊息: NotifyForAlertGroupsError: no active alert groups

原因: Prometheus の alerts.yml と Alertmanager の設定が連携していない場合に発生します。

# 排查步骤

1. Prometheus の alerts 状态を Web UI で确认 (http://localhost:9090/alerts)

2. Alertmanager の状态确认

curl http://localhost:9093/api/v1/status

3. prometheus.yml の alerting.alertmanagers.targets 確認

正例:

alerting:

alertmanagers:

- static_configs:

- targets: ['alertmanager:9093'] # コンテナ名は correct

4. Alertmanager の route 設定確認

route の receiver 名と receivers の name が一致することを確認

エラー3: API 速率制限による误った告警

错误訊息: APIHighLatency Alert - false positive

原因: 网络延迟や速率限制导致的延迟をエラーとして误検知しています。

# 解决方案: 调整阈值和添加过滤条件

alerts.yml を修正

rules: - alert: APIHighLatency expr: | api_request_duration_seconds > 2 and rate(api_errors_total{error_type!="rate_limit"}[5m]) == 0 for: 3m # 延长评估时间,减少误报 labels: severity: warning annotations: summary: "API 响应时间过长(速率限制除外)" description: "延迟 {{ $value }}s,3分钟内持续超过阈值"

或添加速率限制特殊处理

- alert: RateLimitDelay expr: api_request_duration_seconds > 2 and api_rate_limit_remaining == 0 for: 1m labels: severity: info # 降级为信息级别 annotations: summary: "速率限制导致的延迟" description: "API 延迟增加是因为速率限制,即将重置"

エラー4: Grafana の Prometheus データソース接続エラー

错误訊息: Connect timeout error

原因: Grafana と Prometheus のネットワーク接続が確立されていない場合に発生します。

# 解决方案: Docker ネットワーク確認

1. ネットワーク一覧確認

docker network ls

2. コンテナネットワーク確認

docker inspect prometheus | grep Networks docker inspect grafana | grep Networks

3. 同じネットワークにいるか確認

docker-compose.yml で networks 設定を追加:

services: prometheus: networks: - monitoring grafana: networks: - monitoring networks: monitoring: driver: bridge

4. Grafana の Data Source URL をコンテナネットワーク名に修正

URL: http://prometheus:9090 (IPアドレスではなくサービス名を使用)

まとめ:监控で API 運用を確実に

本記事では Prometheus + Alertmanager を使った API 监控告警の構築方法を紹介しました。ポイントをまとめると:

HolySheep AI なら ¥1=$1 の圧倒的なコストパフォーマンスで、监控システム自体のコストも大幅削減できます。<50ms の低延迟で误报も减り安定した监控が可能です。

まずは小さく始めて、少しずつ监控の精度を上げていくことをおすすめします。私の经验では、3ヶ月运用すると监控のコスト対効果が明确になります。

👉 HolySheep AI に登録して無料クレジットを獲得