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

如何通过Terraform Google provider创建基于日志的告警策略

如何通过Terraform Google Provider创建基于日志的告警策略

核心实现逻辑

基于日志的告警不需要预先创建自定义日志指标,直接在告警策略的条件规则中定义日志匹配过滤器即可,对应Terraform资源google_monitoring_alert_policy的condition_matched_log配置项,就是「Logs类型」告警的配置入口。

完整配置示例

# 告警通知渠道示例,可根据实际需求替换为已有的通知渠道ID
resource "google_monitoring_notification_channel" "email_alert" {
  display_name = "运维邮件通知"
  type         = "email"
  labels = {
    email_address = "ops@example.com"
  }
}

# 基于日志的告警策略
resource "google_monitoring_alert_policy" "log_based_alert" {
  display_name = "错误日志告警"
  combiner     = "OR"
  enabled      = true

  # 告警通知文档,可选配置
  documentation {
    content  = "检测到指定服务出现高频错误日志,请及时排查"
    mime_type = "text/markdown"
  }

  condition {
    display_name = "匹配到ERROR级别日志"

    # 日志匹配条件核心配置
    condition_matched_log {
      # 日志过滤规则,和GCP控制台日志查询语法一致,示例为匹配CloudRun服务的ERROR级别日志
      filter = <<EOF
resource.type="cloud_run_revision"
severity="ERROR"
resource.labels.service_name="your-service-name"
EOF

      # 统计时间窗口,示例为5分钟
      duration = "300s"

      # 触发阈值:指定窗口内匹配到1条及以上日志就触发告警
      trigger {
        count = 1
      }
    }
  }

  # 关联通知渠道
  notification_channels = [
    google_monitoring_notification_channel.email_alert.name
  ]
}

关键配置说明

  • condition_matched_log.filter:填写你需要匹配的日志查询规则,语法和GCP日志浏览器的查询语法完全一致,可以先在控制台调试好过滤规则后直接复制到该字段
  • duration:日志统计的时间窗口,最长支持86400s(24小时)
  • trigger.count:在指定时间窗口内匹配到对应日志的数量阈值,达到该阈值就会触发告警

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 08:48:03