> ## Documentation Index
> Fetch the complete documentation index at: https://docs.shannon.run/llms.txt
> Use this file to discover all available pages before exploring further.

# 监控和可观测性

> 监控 Shannon 任务执行和系统健康

<Note>
  监控文档正在开发中。以下概述了核心概念。
</Note>

## 概述

Shannon 提供全面的监控和可观测性功能，以跟踪生产环境中的任务执行、系统性能和资源使用。

## 监控能力

### 任务监控

跟踪单个任务执行：

* 执行状态和进度
* 资源消耗
* 错误率和类型
* 延迟指标
* 成本跟踪

### 系统监控

监控 Shannon 基础设施：

* 服务健康状态
* API 端点延迟
* 队列深度
* 智能体可用性
* LLM 提供商状态

## 指标

### 任务指标

| 指标                       | 描述         | 单位 |
| ------------------------ | ---------- | -- |
| `task.latency`           | 端到端任务完成时间  | 毫秒 |
| `task.cost`              | 每个任务的总成本   | 美元 |
| `task.tokens.input`      | 消耗的输入Token | 数量 |
| `task.tokens.output`     | 生成的输出Token | 数量 |
| `task.iterations`        | 智能体迭代次数    | 数量 |
| `task.tools.invocations` | 工具使用次数     | 数量 |

### 系统指标

| 指标              | 描述       | 单位   |
| --------------- | -------- | ---- |
| `api.latency`   | API 响应时间 | 毫秒   |
| `api.requests`  | 请求速率     | 请求/秒 |
| `api.errors`    | 错误率      | 错误/秒 |
| `queue.depth`   | 等待的任务    | 数量   |
| `agents.active` | 活动智能体数量  | 数量   |

## 健康检查

### API 健康

```bash theme={null}
curl http://localhost:8080/health
```

响应（网关）：

```json theme={null}
{
  "status": "healthy",
  "version": "0.3.0",
  "time": "2025-01-20T10:00:00Z",
  "checks": {
    "gateway": "ok"
  }
}
```

就绪检查（检测编排器连通性）：

```bash theme={null}
curl http://localhost:8080/readiness
```

响应：

```json theme={null}
{
  "status": "ready",
  "version": "0.3.0",
  "time": "2025-01-20T10:00:02Z",
  "checks": {
    "orchestrator": "ok"
  }
}
```

### 组件健康

```python theme={null}
import requests

health = requests.get("http://localhost:8080/health").json()
print("网关：", health.get("status"), health.get("checks"))

ready = requests.get("http://localhost:8080/readiness").json()
print("就绪：", ready.get("status"), ready.get("checks"))
```

## 日志

### 日志级别

Shannon 使用结构化日志记录，级别包括：

* `DEBUG` - 详细诊断信息
* `INFO` - 一般操作消息
* `WARN` - 警告条件
* `ERROR` - 错误条件
* `FATAL` - 严重故障

### 日志格式

```json theme={null}
{
  "timestamp": "2024-10-27T10:00:00Z",
  "level": "INFO",
  "service": "orchestrator",
  "task_id": "task-dev-1730000000",
  "message": "任务已提交",
  "metadata": {
    "mode": "standard",
    "estimated_cost": 0.15
  }
}
```

## 仪表板

### 任务仪表板

实时监控任务执行：

* 活动任务
* 完成率
* 平均延迟
* 错误率
* 每小时成本

### 系统仪表板

跟踪系统健康：

* 服务状态
* 资源利用率
* 队列长度
* 提供商可用性

## 告警

### 告警类型

配置告警以监控：

* 任务失败
* 预算超支
* 高延迟
* 服务降级
* 速率限制

### 告警配置

```yaml theme={null}
alerts:
  - name: high_error_rate
    condition: error_rate > 0.05
    action: notify
    channels: [email, slack]

  - name: budget_warning
    condition: daily_cost > 100
    action: notify
    channels: [email]

  - name: service_down
    condition: health_check_failed
    action: page
    channels: [pagerduty]
```

## Prometheus 集成

将指标导出到 Prometheus（本地开发示例）：

```yaml theme={null}
# prometheus.yml
scrape_configs:
  - job_name: 'orchestrator'
    static_configs:
      - targets: ['localhost:2112']   # Go Orchestrator /metrics

  - job_name: 'agent_core'
    static_configs:
      - targets: ['localhost:2113']   # Rust Agent Core /metrics

  - job_name: 'llm_service'
    metrics_path: '/metrics'
    static_configs:
      - targets: ['localhost:8000']   # Python LLM Service /metrics
```

### 可用指标

```
# HELP shannon_task_total 任务总数
# TYPE shannon_task_total counter
shannon_task_total{status="completed"} 1234
shannon_task_total{status="failed"} 12

# HELP shannon_task_duration_seconds 任务执行时长
# TYPE shannon_task_duration_seconds histogram
shannon_task_duration_seconds_bucket{le="1.0"} 100
shannon_task_duration_seconds_bucket{le="5.0"} 450
```

## Grafana 仪表板

预构建的 Grafana 仪表板用于：

* 任务分析
* 成本跟踪
* 性能监控
* 错误分析

## OpenTelemetry

Shannon 支持 OpenTelemetry 进行分布式跟踪：

```python theme={null}
from opentelemetry import trace
from shannon import ShannonClient

tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("analyze_data"):
    client = ShannonClient()
    handle = client.submit_task(query="分析数据集")
    result = client.get_status(handle.task_id)
```

## 最佳实践

1. **设置告警**以监控关键指标
2. **监控成本**以防止预算超支
3. **跟踪错误模式**以识别问题
4. **使用分布式跟踪**进行调试
5. **归档日志**以满足合规性要求
6. **为您的用例创建自定义仪表板**
7. **实施 SLO**以确保可靠性

## 调试

### 启用调试日志

```python theme={null}
import logging
logging.basicConfig(level=logging.DEBUG)

# 现在 Shannon 将输出详细日志
client = ShannonClient()
```

### 跟踪请求

通过 OpenTelemetry 使用分布式追踪或提高服务日志级别。根据您的可观测性堆栈（Jaeger/Tempo）配置导出器。

## 下一步

<CardGroup cols={2}>
  <Card title="故障排除" icon="wrench" href="/cn/quickstart/troubleshooting">
    常见问题和解决方案
  </Card>

  <Card title="成本控制" icon="dollar" href="/cn/quickstart/concepts/cost-control">
    管理和优化成本
  </Card>
</CardGroup>
