---
document_type: "architecture_design"
service: "MOMENTRY_CORE"
title: "監控系統實戰部署指南"
date: "2026-04-25"
version: "V1.0"
status: "active"
owner: "Warren"
created_by: "OpenCode"
tags:
  - "監控系統實戰部署指南"
ai_query_hints:
  - "查詢 監控系統實戰部署指南 的內容"
  - "監控系統實戰部署指南 的主要目的是什麼？"
  - "如何操作或實施 監控系統實戰部署指南？"
---

# 監控系統實戰部署指南

## 1. 快速部署方案

### 1.1 Docker Compose 部署

創建 `docker-compose.monitoring.yml`：

```yaml
version: '3.8'
services:
  prometheus:
    image: prom/prometheus:latest
    container_name: momentry_prometheus
    restart: unless-stopped
    volumes:
      - ./monitoring/prometheus:/etc/prometheus
    ports:
      - "9090:9090"
    networks:
      - monitoring

  grafana:
    image: grafana/grafana:latest
    container_name: momentry_grafana
    restart: unless-stopped
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
    volumes:
      - ./monitoring/grafana:/var/lib/grafana
    ports:
      - "3000:3000"
    networks:
      - monitoring
    depends_on:
      - prometheus

networks:
  monitoring:
    driver: bridge
```

### 1.2 創建配置文件

```bash
mkdir -p monitoring/prometheus

cat > monitoring/prometheus/prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'momentry-api'
    static_configs:
      - targets: ['host.docker.internal:3002']
    metrics_path: '/metrics'
    scrape_interval: 30s
EOF
```

### 1.3 啟動監控系統

```bash
docker-compose -f docker-compose.monitoring.yml up -d
```

**訪問地址**：
- **Grafana**: http://localhost:3000 (帳號: admin, 密碼: admin)
- **Prometheus**: http://localhost:9090

---

## 2. Momentry Core 指標集成

### 2.1 添加 Prometheus 依賴

在 `Cargo.toml` 中添加：

```toml
[dependencies]
prometheus = "0.13"
```

### 2.2 創建指標模塊

創建 `src/core/metrics/mod.rs`：

```rust
use prometheus::{self, Encoder, TextEncoder, Gauge, Counter, Registry};

lazy_static::lazy_static! {
    pub static ref API_REQUESTS_TOTAL: Counter = register_counter!(
        "momentry_api_requests_total",
        "API 請求總數"
    ).unwrap();

    pub static ref ACTIVE_CONNECTIONS: Gauge = register_gauge!(
        "momentry_active_connections",
        "活躍連接數"
    ).unwrap();
}

pub static REGISTRY: Lazy<Registry> = Lazy::new(|| {
    let registry = Registry::new();
    registry.register(Box::new(API_REQUESTS_TOTAL.clone())).unwrap();
    registry.register(Box::new(ACTIVE_CONNECTIONS.clone())).unwrap();
    registry
});

pub fn gather_metrics() -> String {
    let metric_families = REGISTRY.gather();
    let encoder = TextEncoder::new();
    let mut buffer = vec![];
    encoder.encode(&metric_families, &mut buffer).unwrap();
    String::from_utf8(buffer).unwrap()
}
```

### 2.3 添加 API 指標端點

在 API 路由中添加：

```rust
use axum::{Router, routing::get, response::IntoResponse};
use crate::core::metrics;

pub fn metrics_routes() -> Router {
    Router::new().route("/metrics", get(metrics_handler))
}

async fn metrics_handler() -> impl IntoResponse {
    (
        [(axum::http::header::CONTENT_TYPE, "text/plain; version=0.0.4")],
        metrics::gather_metrics(),
    )
}
```

---

## 3. 生產部署建議

### 3.1 安全配置

1. **更改默認密碼**
   ```bash
   # 更改 Grafana 管理員密碼
   docker exec momentry_grafana grafana-cli admin reset-admin-password newpassword
   ```

2. **啟用 HTTPS**
   ```yaml
   grafana:
     environment:
       - GF_SERVER_PROTOCOL=https
   ```

### 3.2 監控項目

| 監控項目 | 指標名稱 | 告警閾值 |
|----------|----------|----------|
| API 請求數 | `momentry_api_requests_total` | N/A |
| 活躍連接數 | `momentry_active_connections` | >100 |
| 錯誤率 | `momentry_api_errors_total` | >10% |
| 響應時間 | `momentry_api_response_time` | >1s |

---

**最後更新**: 2026-04-22  
**部署時間**: 10-30 分鐘
