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

# 自动排查 Datadog 告警

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="自动分析 Datadog 告警" description="将 PagerDuty 或 Datadog 告警接入 Devin，实现自动化的事件排查。" prompt="帮我搭建一个从 Datadog 到 Devin 的告警分析流水线。请按照 https://docs.devin.ai/use-cases/gallery/api-datadog-alert-investigation 中的指南，一步步带我完成每个步骤：启用 Datadog MCP、创建 webhook 处理器，并将其连接到我的 Datadog 监控。" category="事件响应" features="API, MCP" />

<div className="uc-detail-wrapper">
  <Tip>如需更详细的 Datadog 集成指南，请[点击此处](/zh/enterprise/integrations/datadog)。</Tip>

  <Steps>
    <Step title="启用 Datadog MCP">
      Devin 需要访问你的 Datadog 账户，以便在排查问题时查询日志、指标和监控。

      1. 前往 **Settings > Connections > MCP servers** 并找到 **Datadog**
      2. 点击 **Enable**，选择你的 Datadog 站点/区域，并输入你的 `DD-API-KEY` 和 `DD-APPLICATION-KEY` —— 可在 [Datadog > Organization Settings > API Keys](https://app.datadoghq.com/organization-settings/api-keys) 中生成这些密钥
      3. 点击 **Test listing tools** 以验证 Devin 是否能够成功连接

      启用后，Devin 可以在单次会话中查询错误日志、拉取指标时间序列数据、列出活动监控项并搜索追踪。了解更多关于[连接 MCP 服务器](/zh/work-with-devin/mcp)的信息。
    </Step>

    <Step title="构建告警到 Devin 的桥接通道">
      你需要一个小型服务，用于接收告警 webhook，并通过 [Devin API](/zh/api-reference/overview) 发起 Devin 会话。将其部署为无服务器函数 (AWS Lambda、Cloudflare Worker) 或轻量级容器：

      ```python theme={null}
      from flask import Flask, request, jsonify
      import requests, os

      app = Flask(__name__)

      @app.route("/alert", methods=["POST"])
      def handle_alert():
          payload = request.json

          # Datadog webhook 载荷字段
          alert_title = payload.get("title", "Unknown alert")
          tags_str = payload.get("tags", "")
          service = next(
              (t.split(":", 1)[1] for t in tags_str.split(",") if t.strip().startswith("service:")),
              "unknown-service"
          )
          alert_url = payload.get("link", "")

          org_id = os.environ["DEVIN_ORG_ID"]
          response = requests.post(
              f"https://api.devin.ai/v3/organizations/{org_id}/sessions",
              headers={"Authorization": f"Bearer {os.environ['DEVIN_API_KEY']}"},
              json={
                  "prompt": (
                      f"Datadog alert fired: '{alert_title}'\n"
                      f"Service: {service}\n"
                      f"Alert link: {alert_url}\n\n"
                      "Using the Datadog MCP:\n"
                      "1. Pull error logs for this service from the past 30 min\n"
                      "2. Identify the top error messages and stack traces\n"
                      "3. Check if this correlates with a recent deploy\n"
                      "4. If the root cause is clear, open a hotfix PR\n"
                      "5. Post your findings to #incidents on Slack"
                  ),
                  "playbook_id": "14fed18b89d44713a26e673cf258f548",
              }
          )
          return jsonify(response.json()), 200
      ```

      在 [app.devin.ai](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) 的 **Settings > Service Users** 中创建一个[服务用户](/zh/api-reference/v3/overview)，并授予 `ManageOrgSessions` 权限。复制创建后显示的 API 令牌，并将其作为 `DEVIN_API_KEY` 存储在你的桥接服务中。将 `DEVIN_ORG_ID` 设置为你的组织 ID —— 使用你的令牌调用 `GET https://api.devin.ai/v3/enterprise/organizations` 来获取该值。

      上面的代码使用了 [`!triage` 模板 playbook](https://app.devin.ai/settings/playbooks/14fed18b89d44713a26e673cf258f548?utm_source=docs\&utm_medium=use-case-gallery) —— 复制一份，并根据你的技术栈自定义排查步骤，然后在你的桥接服务中更新 `playbook_id`。
    </Step>

    <Step title="将告警路由到 Webhook 端点">
      **直接在 Datadog 中配置：**

      1. 在 Datadog 仪表板中，进入 **Integrations > Webhooks**
      2. 点击 **New Webhook**，并将 URL 设置为你的 bridge endpoint (例如：`https://your-bridge.example.com/alert`)
      3. 在任意监控的通知消息中添加 `@webhook-devin-bridge` —— 每当该监控触发时，Devin 都会进行排查

      **从 PagerDuty 配置：**

      1. 在 PagerDuty 中，进入 **Services > \[your service] > Integrations**
      2. 添加一个 **Generic Webhooks (v3)** 集成
      3. 将 webhook URL 设置为你的 bridge endpoint，并按事件类型 `incident.triggered` 进行过滤

      先从 warning 级别的监控开始，用来测试整个流程，然后再路由关键告警。
    </Step>

    <Step title="Devin 会分析什么">
      当告警触发一个会话时，Devin 使用 Datadog MCP 来执行结构化排查——查询日志、关联部署变更，并将错误追溯到源代码。

      <PromptBlock>
        ```txt Investigate Datadog alert theme={null}
        Datadog alert: "payments-service 错误率高 (5.2%，阈值 1%)"
        于 2026-02-10 14:32 UTC 触发。

        使用 Datadog MCP：
        1. 获取过去 30 分钟内 payments-service 的错误日志
        2. 按错误信息分组——主要故障是什么？
        3. 查看 Datadog 事件中是否有对 payments-service 的近期部署
        4. 阅读相关源代码以及失败路径上最近的提交
        5. 如果可以修复，则提交一个热修复 PR。否则，将调查结论发布到 #incidents。
        ```
      </PromptBlock>

      Devin 在 Slack 中发布的示例排查结果：

      ```
      告警调查：payments-service 错误率飙升

      时间线：
      - 14:28 UTC — Deploy #492 发布（commit abc123f）
      - 14:31 UTC — 错误率从 0.3% 跃升至 5.2%
      - 14:32 UTC — 告警触发

      根本原因：Deploy #492 将 Stripe webhook 处理程序
      （src/webhooks/stripe.ts）重构为 async/await，但移除了
      handlePaymentIntent() 外层的 try/catch。未处理的 rejection 导致
      约 4% 的结账请求返回 500 错误。

      修复方案：添加了错误边界，引入结构化日志记录，并对客户端错误返回
      规范的 4xx 响应。

      PR #493 已创建 → https://github.com/acme/payments/pull/493
      ```
    </Step>

    <Step title="扩展流水线">
      在基础排查流程跑通后，再逐步叠加更多自动化能力：

      **自定义分诊手册 (triage playbook) 。** bridge 代码已经在使用 [`!triage` 模板 playbook](https://app.devin.ai/settings/playbooks/14fed18b89d44713a26e673cf258f548?utm_source=docs\&utm_medium=use-case-gallery)。复制一份，并根据你团队的技术栈定制排查清单——添加各服务专属的运行手册、升级路径，以及紧急修复 PR (拉取请求) 的处理规范。

      **按严重级别划分处理策略。** 将 P1 告警路由为需要立刻排查并紧急修复的事件。将 P3 告警仅路由为根因分析使用。针对不同严重级别使用不同的提示词或 playbook。

      **为你的服务添加 [Knowledge](/zh/product-guides/knowledge)** ——例如正常阈值、架构说明、值班运行手册——这样 Devin 的排查就能从你团队的上下文出发，而不是从零开始。
    </Step>
  </Steps>
</div>
