You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Django迁移失败配置告警(支持Datadog/Sentry/GitHub Action)

Django生产环境迁移失败告警方案

针对你的Django应用部署流程(PR合并main触发GitHub Action发布),以下是三种可行的迁移失败告警方案,分别基于GitHub Action、Sentry和Datadog:

方案一:GitHub Action 原生告警

直接在部署工作流中捕获迁移失败事件,触发通知或创建问题,无需额外工具集成:

  1. 修改GitHub Action部署yaml文件,在迁移步骤后添加失败处理逻辑:
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      # 省略拉取代码、安装依赖等前置步骤
      
      - name: Run Django Production Migrations
        id: django_migrate
        run: |
          set -e
          # 替换为你的生产环境迁移执行命令(如SSH连接服务器/容器内执行)
          ssh prod-server "cd /path/to/app && source venv/bin/activate && python manage.py migrate --noinput"
        continue-on-error: true

      - name: Create Migration Failure Issue
        if: steps.django_migrate.outcome == 'failure'
        uses: actions/github-script@v6
        with:
          script: |
            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: '🚨 生产环境Django迁移失败',
              body: `提交哈希:${context.sha}\n部署工作流链接:${context.runUrl}\n请立即查看日志排查问题`
            })

      # 可选:添加Slack/Teams即时通知
      - name: Notify Slack on Migration Failure
        if: steps.django_migrate.outcome == 'failure'
        uses: slackapi/slack-github-action@v1.24.0
        with:
          payload: |
            {
              "text": "⚠️ 生产环境Django迁移失败!\n提交:${{ github.sha }}\n日志:${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
            }
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
  1. 优势:完全复用现有部署流程,配置简单,无额外监控工具成本。

方案二:Sentry 异常捕获告警

利用Sentry捕获迁移过程中的异常,并配置专属告警规则:

  1. 确保Django项目已集成Sentry SDK(未集成则先完成基础配置)
  2. 编写迁移执行包装脚本,确保异常被Sentry捕获:
# migrate_with_sentry.py
import sentry_sdk
from django.core.management import execute_from_command_line
import os

# 初始化Sentry(直接读取环境变量)
sentry_sdk.init(
    dsn=os.environ.get("SENTRY_DSN"),
    environment="production",
    traces_sample_rate=1.0,
)

try:
    execute_from_command_line(["manage.py", "migrate", "--noinput"])
except Exception as exc:
    # 手动上报异常至Sentry
    sentry_sdk.capture_exception(exc)
    # 抛出异常终止部署流程
    raise
  1. 在部署工作流中替换原迁移命令为python migrate_with_sentry.py
  2. 在Sentry后台配置告警规则:
    • 创建新规则,过滤条件选择transaction:manage.py migrate且event.level:error
    • 设置通知渠道(邮件、Slack等),触发规则时立即推送告警

方案三:Datadog 指标/日志告警

通过Datadog监控迁移状态或日志,实现告警:

方式1:自定义指标监控

  1. 在GitHub Action部署工作流中,发送迁移结果指标到Datadog:
- name: Report Migration Status to Datadog
  if: always()
  uses: DataDog/datadog-ci@v1
  with:
    api_key: ${{ secrets.DATADOG_API_KEY }}
    command: metrics send -t gauge -m django.production.migrate.success -v ${{ steps.django_migrate.outcome == 'success' && 1 || 0 }} -t env:production -t service:django
  1. 在Datadog后台创建监控:
    • 选择"Metric Alert",指标选择django.production.migrate.success
    • 设置告警条件为指标值等于0,触发通知

方式2:日志告警

  1. 确保生产环境的迁移日志已通过Datadog Agent收集至Datadog
  2. 在Datadog后台创建日志监控:
    • 日志查询语句:service:django env:production "Migration failed" OR "OperationalError"
    • 设置告警条件为"出现至少1条匹配日志",触发通知

额外建议

  • 部署前先在staging环境执行相同迁移操作,提前发现潜在问题
  • 在PR合并前的CI流程中,添加针对测试数据库的迁移执行步骤,拦截明显错误

内容的提问来源于stack exchange,提问作者Koti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:20:30