使用 API 创建提醒政策

在 Cloud Monitoring API 中,提醒政策由 AlertPolicy 对象表示,该对象描述一组指示系统可能存在非健康状况的条件。

本文档介绍了以下内容:

  • Monitoring API 如何表示提醒政策。
  • Monitoring API 为提醒政策提供的条件类型。
  • 如何使用 Google Cloud CLI 或客户端库创建提醒政策。

提醒政策的结构

AlertPolicy 结构定义提醒政策的组成部分。创建政策时,您需要为以下 AlertPolicy 字段指定值:

  • displayName:政策的描述性标签。
  • documentation:为帮助回复者提供的任何信息。此字段是可选字段。documentation 对象包含以下内容:
    • content:用户定义的文本,显示在通知正文中。
    • subject:通知的主题行。主题行不得超过 255 个字符。
  • userLabels:附加到政策的任何用户定义的标签。如需了解如何使用带有提醒的标签,请参阅使用标签来注释提醒
  • conditions[]:一组 Condition 结构。
  • combiner:用于确定如何处理多个条件的逻辑运算符。
  • notificationChannels[]:一组资源名称,每个资源名称都标识一个 NotificationChannel
  • alertStrategy:指定当数据停止到达时,Monitoring 关闭突发事件的速度。此对象还指定是否为基于指标的提醒启用重复通知,以及这些通知之间的时间间隔。如需了解详情,请参阅 [发送重复的通知][重复通知]。

您还可以在使用 Cloud Monitoring API 和 Google Cloud 控制台时指定 severity 字段。通过此字段,您可以定义突发事件的严重级别。如果您未指定严重性,Cloud Monitoring 会将提醒政策严重性设置为 No Severity

根据您创建的条件,您可以使用其他字段。

如果提醒政策包含一个条件,那么当满足该条件时,系统会发送通知。如需了解提醒政策包含多个条件时的通知,请参阅包含多个条件的政策每个政策的通知数量

当您创建或修改提醒政策时,Monitoring 还会设置其他字段,包括 name 字段。name 字段的值是提醒政策的资源名称,用于标识政策。该资源名称采用以下格式:

projects/PROJECT_ID/alertPolicies/POLICY_ID

API 中的条件类型

Cloud Monitoring API 支持 Condition 结构中的各种条件类型。基于指标的提醒政策有多种条件类型,基于日志的提醒政策有一种条件类型。以下各部分介绍了可用的条件类型。

基于指标的提醒政策的条件

如需创建提醒政策来监控指标数据(包括基于日志的指标),您可以使用以下条件类型:

基于过滤条件的指标条件

MetricAbsenceMetricThreshold 条件使用 Monitoring 过滤条件选择要监控的时序数据。条件结构中的其他字段指定如何过滤、分组和聚合数据。如需详细了解这些概念,请参阅过滤和聚合:处理时序

如果使用 MetricAbsence 条件类型,则可以创建一个仅当所有时序都不存在时才满足的条件。此条件使用 aggregations 参数将多个时序聚合到单个时序。如需了解详情,请参阅 API 文档中的 MetricAbsence 参考文档。

指标缺失提醒政策要求之前已写入一些数据;如需了解详情,请参阅创建指标缺失提醒政策

如果您希望根据预测值收到通知,请将提醒政策配置为使用 MetricThreshold 条件类型并设置 forecastOptions 字段。如果未设置此字段,则测量数据将与阈值进行比较。不过,如果设置了此字段,则预测数据将与阈值进行比较。如需了解详情,请参阅创建预测的指标值提醒政策

基于 MQL 的指标条件

MonitoringQueryLanguageCondition 条件使用 Monitoring Query Language (MQL) 来选择和操纵要监控的时序数据。您可以创建提醒政策,用于根据阈值比较值或测试此条件类型的值是否缺失。如果您使用 MonitoringQueryLanguageCondition 条件,则该条件必须是提醒政策中的唯一条件。如需了解详情,请参阅使用 MQL 的提醒政策

基于 PromQL 的指标条件

PrometheusQueryLanguageCondition 条件使用 Prometheus 查询语言 (PromQL) 查询来选择和操控要监控的时间序列数据。您可以创建简单或复杂的查询,并使用动态阈值、比率、指标比较等查询结构。

如果使用 PrometheusQueryLanguageCondition 条件,该条件必须是提醒政策中的唯一条件。如需了解详情,请参阅使用 PromQL 的提醒政策

基于比率的提醒条件

您可以创建指标阈值提醒政策来监控两个指标的比率。您可以使用 MetricThresholdMonitoringQueryLanguageCondition 条件类型创建这些政策。您还可以直接在 Google Cloud 控制台中使用 MQL。您无法通过使用图形界面创建阈值条件来创建或管理基于比率的条件。

我们建议使用 MQL 来创建基于比率的提醒政策。与使用 MetricTheshold 条件类型和 Monitoring 过滤条件相比,MQL 可让您构建更强大、更灵活的查询。例如,使用 MonitoringQueryLanguageCondition 条件时,您可以计算衡量指标与增量指标的比率。如需查看示例,请参阅 MQL 提醒政策示例

如果您使用 MetricThreshold 条件,则比率的分子和分母必须具有相同的 MetricKind。有关指标及其属性的列表,请参阅 指标列表

通常,最好根据为单个指标类型收集的时序使用标签值计算比率。针对两种不同指标类型计算的比率可能会因采样周期和校准时段不同而出现异常。

例如,假设您有两个不同的指标类型,一个是 RPC 总数,一个是 RPC 错误数量,并且您想要计算错误 RPC 与总 RPC 的比率。失败的 RPC 会计入这两个指标类型的时序中。因此,当您校准时序时,某个失败的 RPC 可能不会出现在两个时序的同一校准间隔中。导致这种差异的原因有很多,包括:

  • 由于两个不同的时序记录同一事件,因此有两个计数器值在实现集合,并且它们不会以原子方式更新。
  • 采样率可能会不一样。当时序与公共时间段校准时,单个事件的计数可能会出现在不同指标的时序的相邻校准间隔中。

相应校准间隔内值的数量差可能导致无意义的 error/total 比率值,例如 1/0 或 2/1。

数值较大的比率不太可能产生无意义的值。 您可以通过聚合获得更大的数字,方法是使用长于采样周期的校准时段,或针对特定标签的数据分组。这些方法可以最大限度地减少给定时间间隔中数据点数量的微小差异的影响。也就是说,在一个时间间隔内,预期数据点数量为 3 时的两点间差异会比预期数量为 300 时更明显。

如果您使用的是内置指标类型,则可能只能计算不同指标类型的比率以获得所需的值。

如果您设计的自定义指标可能会在两个不同的指标中统计相同的内容(例如,返回错误状态的 RPC 数量),请考虑使用单个指标,以使每个计数仅被包含一次。例如,假设您在统计 RPC 数量并想要跟踪失败的 RPC 与所有 RPC 之比。要解决此问题,请创建单个指标类型来统计 RPC 数量,然后使用标签来记录调用状态,包括“成功”状态。然后,通过更新单个计数器即可记录每个状态值(在此例中为“错误”或“成功”)。

基于日志的提醒政策的条件

如需创建基于日志的提醒政策(该政策在您的日志条目中出现符合过滤条件的消息时通知您),请使用 LogMatch 条件类型。如果您使用 LogMatch 条件,则该条件必须是提醒政策中的唯一条件。

请勿尝试将 LogMatch 条件类型与基于日志的指标结合使用。监控基于日志的指标的提醒政策是基于指标的政策。如需详细了解如何选择用于监控基于日志的指标或日志条目的提醒政策,请参阅监控日志

使用 API 管理提醒政策文档的示例中使用的提醒政策是基于指标的提醒政策,但基于日志的提醒政策的原则相同。如需了解基于日志的提醒政策的特定信息,请参阅 Cloud Logging 文档中的使用 Monitoring API 创建基于日志的提醒

准备工作

在针对该 API 编写代码之前,您应该满足以下条件:

  • 熟悉提醒政策的一般概念和所用术语;如需了解详情,请参阅提醒概览
  • 确保已启用 Cloud Monitoring API;如需了解详情,请参阅启用 API
  • 如果您打算使用客户端库,请安装您要使用的语言的库;如需了解详情,请参阅客户端库。 目前,此 API 仅支持针对 C#、Go、Java、Node.js 和 Python 的提醒。
  • 如果您打算使用 Google Cloud CLI,请进行安装。 但是,如果您使用 Cloud Shell,则 Google Cloud CLI 已经安装。

    此处还提供了使用 gcloud 界面的示例。 请注意,gcloud 示例都假设当前项目已被设置为目标 (gcloud config set project [PROJECT_ID]),因此调用中省略了显式 --project 标志。示例中当前项目的 ID 为 a-gcp-project

创建提醒政策

如需在项目中创建提醒政策,请使用 alertPolicies.create 方法。如需了解如何调用此方法、其参数和响应数据,请参阅参考页面 alertPolicies.create

您可以利用 JSON 或 YAML 文件创建政策。 Google Cloud CLI 接受这些文件作为参数,并且您可以通过编程方式读取 JSON 文件,将其转换为 AlertPolicy 对象,并使用 alertPolicies.create 方法根据这些对象创建政策。如果您的 Prometheus JSON 或 YAML 配置文件包含提醒规则,则 gcloud CLI 可将其迁移到具有 PromQL 条件的 Cloud Monitoring 提醒政策。如需了解详情,请参阅从 Prometheus 迁移提醒规则和接收器

每个提醒政策都属于指标范围限定项目。每个项目最多可以包含 500 个政策。对于 API 调用,您必须提供“项目 ID”;使用指标范围限定项目的 ID 作为值。在这些示例中,指标范围限定项目的 ID 为 a-gcp-project

以下示例介绍如何创建提醒政策,但未说明如何创建可描述提醒政策的 JSON 或 YAML 文件。相反,这些示例假定存在 JSON 格式的文件,并说明了如何发出 API 调用。如需查看示例 JSON 文件,请参阅示例政策。如需了解有关监控指标比率的一般信息,请参阅指标比率

gcloud

要在项目中创建提醒政策,请使用 gcloud alpha monitoring policies create 命令。以下示例利用 rising-cpu-usage.json 文件在 a-gcp-project 中创建了提醒政策:

gcloud alpha monitoring policies create --policy-from-file="rising-cpu-usage.json"

如果成功,则该命令将返回新政策的名称,例如:

Created alert policy [projects/a-gcp-project/alertPolicies/12669073143329903307].

文件 rising-cpu-usage.json 文件包含显示名称为“High CPU rate of change”的政策的 JSON。如需详细了解此政策,请参阅 Rate-of-change 政策

如需了解详情,请查看 gcloud alpha monitoring policies create 参考。

C#

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

static void RestorePolicies(string projectId, string filePath)
{
    var policyClient = AlertPolicyServiceClient.Create();
    var channelClient = NotificationChannelServiceClient.Create();
    List<Exception> exceptions = new List<Exception>();
    var backup = JsonConvert.DeserializeObject<BackupRecord>(
        File.ReadAllText(filePath), new ProtoMessageConverter());
    var projectName = new ProjectName(projectId);
    bool isSameProject = projectId == backup.ProjectId;
    // When a channel is recreated, rather than updated, it will get
    // a new name.  We have to update the AlertPolicy with the new
    // name.  Track the names in this map.
    var channelNameMap = new Dictionary<string, string>();
    foreach (NotificationChannel channel in backup.Channels)
    {
    }
    foreach (AlertPolicy policy in backup.Policies)
    {
        string policyName = policy.Name;
        // These two fields cannot be set directly, so clear them.
        policy.CreationRecord = null;
        policy.MutationRecord = null;
        // Update channel names if the channel was recreated with
        // another name.
        for (int i = 0; i < policy.NotificationChannels.Count; ++i)
        {
            if (channelNameMap.ContainsKey(policy.NotificationChannels[i]))
            {
                policy.NotificationChannels[i] =
                    channelNameMap[policy.NotificationChannels[i]];
            }
        }
        try
        {
            Console.WriteLine("Updating policy.\n{0}",
                policy.DisplayName);
            bool updated = false;
            if (isSameProject)
                try
                {
                    policyClient.UpdateAlertPolicy(null, policy);
                    updated = true;
                }
                catch (Grpc.Core.RpcException e)
                when (e.Status.StatusCode == StatusCode.NotFound)
                { }
            if (!updated)
            {
                // The policy no longer exists.  Recreate it.
                policy.Name = null;
                foreach (var condition in policy.Conditions)
                {
                    condition.Name = null;
                }
                policyClient.CreateAlertPolicy(projectName, policy);
            }
            Console.WriteLine("Restored {0}.", policyName);
        }
        catch (Exception e)
        {
            // If one failed, continue trying to update the others.
            exceptions.Add(e);
        }
    }
    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

Go

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


// restorePolicies updates the project with the alert policies and
// notification channels in r.
func restorePolicies(w io.Writer, projectID string, r io.Reader) error {
	b := backup{}
	if err := json.NewDecoder(r).Decode(&b); err != nil {
		return err
	}
	sameProject := projectID == b.ProjectID

	ctx := context.Background()

	alertClient, err := monitoring.NewAlertPolicyClient(ctx)
	if err != nil {
		return err
	}
	defer alertClient.Close()
	channelClient, err := monitoring.NewNotificationChannelClient(ctx)
	if err != nil {
		return err
	}
	defer channelClient.Close()

	// When a channel is recreated, rather than updated, it will get
	// a new name.  We have to update the AlertPolicy with the new
	// name.  channelNames keeps track of the new names.
	channelNames := make(map[string]string)
	for _, c := range b.Channels {
		fmt.Fprintf(w, "Updating channel %q\n", c.GetDisplayName())
		c.VerificationStatus = monitoringpb.NotificationChannel_VERIFICATION_STATUS_UNSPECIFIED
		updated := false
		if sameProject {
			req := &monitoringpb.UpdateNotificationChannelRequest{
				NotificationChannel: c.NotificationChannel,
			}
			_, err := channelClient.UpdateNotificationChannel(ctx, req)
			if err == nil {
				updated = true
			}
		}
		if !updated {
			req := &monitoringpb.CreateNotificationChannelRequest{
				Name:                "projects/" + projectID,
				NotificationChannel: c.NotificationChannel,
			}
			oldName := c.GetName()
			c.Name = ""
			newC, err := channelClient.CreateNotificationChannel(ctx, req)
			if err != nil {
				return err
			}
			channelNames[oldName] = newC.GetName()
		}
	}

	for _, policy := range b.AlertPolicies {
		fmt.Fprintf(w, "Updating alert %q\n", policy.GetDisplayName())
		policy.CreationRecord = nil
		policy.MutationRecord = nil
		for i, aChannel := range policy.GetNotificationChannels() {
			if c, ok := channelNames[aChannel]; ok {
				policy.NotificationChannels[i] = c
			}
		}
		updated := false
		if sameProject {
			req := &monitoringpb.UpdateAlertPolicyRequest{
				AlertPolicy: policy.AlertPolicy,
			}
			_, err := alertClient.UpdateAlertPolicy(ctx, req)
			if err == nil {
				updated = true
			}
		}
		if !updated {
			req := &monitoringpb.CreateAlertPolicyRequest{
				Name:        "projects/" + projectID,
				AlertPolicy: policy.AlertPolicy,
			}
			if _, err = alertClient.CreateAlertPolicy(ctx, req); err != nil {
				log.Fatal(err)
			}
		}
	}
	fmt.Fprintf(w, "Successfully restored alerts.")
	return nil
}

Java

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

private static void restoreRevisedPolicies(
    String projectId, boolean isSameProject, List<AlertPolicy> policies) throws IOException {
  try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
    for (AlertPolicy policy : policies) {
      if (!isSameProject) {
        policy = client.createAlertPolicy(ProjectName.of(projectId), policy);
      } else {
        try {
          client.updateAlertPolicy(null, policy);
        } catch (Exception e) {
          policy =
              client.createAlertPolicy(
                  ProjectName.of(projectId), policy.toBuilder().clearName().build());
        }
      }
      System.out.println(String.format("Restored %s", policy.getName()));
    }
  }
}

Node.js

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

const fs = require('fs');

// Imports the Google Cloud client library
const monitoring = require('@google-cloud/monitoring');

// Creates a client
const client = new monitoring.AlertPolicyServiceClient();

async function restorePolicies() {
  // Note: The policies are restored one at a time due to limitations in
  // the API. Otherwise, you may receive a 'service unavailable'  error
  // while trying to create multiple alerts simultaneously.

  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  console.log('Loading policies from ./policies_backup.json');
  const fileContent = fs.readFileSync('./policies_backup.json', 'utf-8');
  const policies = JSON.parse(fileContent);

  for (const index in policies) {
    // Restore each policy one at a time
    let policy = policies[index];
    if (await doesAlertPolicyExist(policy.name)) {
      policy = await client.updateAlertPolicy({
        alertPolicy: policy,
      });
    } else {
      // Clear away output-only fields
      delete policy.name;
      delete policy.creationRecord;
      delete policy.mutationRecord;
      policy.conditions.forEach(condition => delete condition.name);

      policy = await client.createAlertPolicy({
        name: client.projectPath(projectId),
        alertPolicy: policy,
      });
    }

    console.log(`Restored ${policy[0].name}.`);
  }
  async function doesAlertPolicyExist(name) {
    try {
      const [policy] = await client.getAlertPolicy({
        name,
      });
      return policy ? true : false;
    } catch (err) {
      if (err && err.code === 5) {
        // Error code 5 comes from the google.rpc.code.NOT_FOUND protobuf
        return false;
      }
      throw err;
    }
  }
}
restorePolicies();

PHP

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition;
use Google\Cloud\Monitoring\V3\AlertPolicy\Condition\MetricThreshold;
use Google\Cloud\Monitoring\V3\AlertPolicy\ConditionCombinerType;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\ComparisonType;
use Google\Cloud\Monitoring\V3\CreateAlertPolicyRequest;
use Google\Protobuf\Duration;

/**
 * @param string $projectId Your project ID
 */
function alert_create_policy($projectId)
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $policy = new AlertPolicy();
    $policy->setDisplayName('Test Alert Policy');
    $policy->setCombiner(ConditionCombinerType::PBOR);
    /** @see https://cloud.google.com/monitoring/api/resources for a list of resource.type */
    /** @see https://cloud.google.com/monitoring/api/metrics_gcp for a list of metric.type */
    $policy->setConditions([new Condition([
        'display_name' => 'condition-1',
        'condition_threshold' => new MetricThreshold([
            'filter' => 'resource.type = "gce_instance" AND metric.type = "compute.googleapis.com/instance/cpu/utilization"',
            'duration' => new Duration(['seconds' => '60']),
            'comparison' => ComparisonType::COMPARISON_LT,
        ])
    ])]);
    $createAlertPolicyRequest = (new CreateAlertPolicyRequest())
        ->setName($projectName)
        ->setAlertPolicy($policy);

    $policy = $alertClient->createAlertPolicy($createAlertPolicyRequest);
    printf('Created alert policy %s' . PHP_EOL, $policy->getName());
}

Python

如需向 Monitoring 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def restore(project_name, backup_filename):
    """Restore alert policies in a project.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        backup_filename (str): Name of the file (along with its path) from
            which the alert policies will be restored.
    """
    print(
        "Loading alert policies and notification channels from {}.".format(
            backup_filename
        )
    )
    record = json.load(open(backup_filename, "rt"))
    is_same_project = project_name == record["project_name"]
    # Convert dicts to AlertPolicies.
    policies_json = [json.dumps(policy) for policy in record["policies"]]
    policies = [
        monitoring_v3.AlertPolicy.from_json(policy_json)
        for policy_json in policies_json
    ]
    # Convert dicts to NotificationChannels
    channels_json = [json.dumps(channel) for channel in record["channels"]]
    channels = [
        monitoring_v3.NotificationChannel.from_json(channel_json)
        for channel_json in channels_json
    ]

    # Restore the channels.
    channel_client = monitoring_v3.NotificationChannelServiceClient()
    channel_name_map = {}

    for channel in channels:
        updated = False
        print("Updating channel", channel.display_name)
        # This field is immutable and it is illegal to specify a
        # non-default value (UNVERIFIED or VERIFIED) in the
        # Create() or Update() operations.
        channel.verification_status = (
            monitoring_v3.NotificationChannel.VerificationStatus.VERIFICATION_STATUS_UNSPECIFIED
        )

        if is_same_project:
            try:
                channel_client.update_notification_channel(notification_channel=channel)
                updated = True
            except google.api_core.exceptions.NotFound:
                pass  # The channel was deleted.  Create it below.

        if not updated:
            # The channel no longer exists.  Recreate it.
            old_name = channel.name
            del channel.name
            new_channel = channel_client.create_notification_channel(
                name=project_name, notification_channel=channel
            )
            channel_name_map[old_name] = new_channel.name

    # Restore the alerts
    alert_client = monitoring_v3.AlertPolicyServiceClient()

    for policy in policies:
        print("Updating policy", policy.display_name)
        # These two fields cannot be set directly, so clear them.
        del policy.creation_record
        del policy.mutation_record

        # Update old channel names with new channel names.
        for i, channel in enumerate(policy.notification_channels):
            new_channel = channel_name_map.get(channel)
            if new_channel:
                policy.notification_channels[i] = new_channel

        updated = False

        if is_same_project:
            try:
                alert_client.update_alert_policy(alert_policy=policy)
                updated = True
            except google.api_core.exceptions.NotFound:
                pass  # The policy was deleted.  Create it below.
            except google.api_core.exceptions.InvalidArgument:
                # Annoying that API throws InvalidArgument when the policy
                # does not exist.  Seems like it should throw NotFound.
                pass  # The policy was deleted.  Create it below.

        if not updated:
            # The policy no longer exists.  Recreate it.
            old_name = policy.name
            del policy.name
            for condition in policy.conditions:
                del condition.name
            policy = alert_client.create_alert_policy(
                name=project_name, alert_policy=policy
            )
        print("Updated", policy.name)

创建的 AlertPolicy 对象将具有其他字段。 该政策本身有 namecreationRecordmutationRecord 字段。此外,政策中的每个条件也都有一个 name。 这些字段不能在外部修改,因此不必在创建政策时设置这些字段。 创建政策的 JSON 示例里都不包含这些字段,但如果有人在示例创建政策后检索这些政策,则这些字段将出现。

为基于指标的提醒政策配置重复通知

默认情况下,当突发事件出现时,基于指标的提醒政策会向每个通知渠道发送一条通知。不过,您可以更改默认行为,并配置提醒政策,以便向提醒政策的所有或部分通知渠道重新发送通知。系统会针对状态为“未结”或“已确认”的突发事件发送这些重复的通知。这些通知之间的时间间隔必须至少为 30 分钟且不超过 24 小时(以秒为单位)。

如需配置重复通知,请在提醒政策的配置中添加包含至少一个 NotificationChannelStrategy 对象的 AlertStrategy 对象。NotificationChannelStrategy 对象有两个字段:

  • renotifyInterval:重复通知之间的时间间隔(以秒为单位)。

    如果您在提醒政策的突发事件发生时更改了 renotifyInterval 字段的值,则会发生以下情况:

    • 提醒政策会再发送一次有关突发事件的通知。
    • 提醒政策会重启间隔时段。
  • notificationChannelNames:通知渠道资源名称的数组,是 projects/PROJECT_ID/notificationChannels/CHANNEL_ID 格式的字符串,其中 CHANNEL_ID 是数值。如需了解如何检索渠道 ID,请参阅列出项目中的通知渠道

例如,以下 JSON 示例展示了一个提醒策略,该策略配置为每 1800 秒(30 分钟)向一个通知渠道发送重复通知:

  "alertStrategy": {
    "notificationChannelStrategy": [
      {
        "notificationChannelNames": [
          "projects/PROJECT_ID/notificationChannels/CHANNEL_ID"
        ],
        "renotifyInterval": "1800s"
      }
    ]
  }

要暂时停止重复发送通知,请创建暂停。为防止出现重复的通知,请使用 API 修改提醒政策并移除 NotificationChannelStrategy 对象。

后续步骤