使用 API 创建提醒政策

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

本文档介绍了以下内容:

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

此功能仅适用于 Google Cloud 项目。对于 App Hub 配置,请选择 App Hub 宿主项目或管理项目。

提醒政策的结构

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

  • displayName:政策的描述性标签。
  • documentation:建议您使用此字段提供可帮助事件响应人员的信息。如需了解详情,请参阅使用用户定义的文档为通知添加注解。
  • userLabels:附加到政策的任何用户定义标签。提醒政策、突发事件和通知均会显示这些标签。如需了解如何将标签与提醒结合使用,请参阅使用标签为突发事件添加注解。

  • conditions[]:一组 Condition 结构。

  • combiner:用于确定如何处理多个条件的逻辑运算符。

  • notificationChannels[]:一组资源名称,每个资源名称都标识一个 NotificationChannel。

  • alertStrategy:指定以下内容:

    • Monitoring 在数据停止到达多长时间后关闭突发事件。
    • 对于基于指标的提醒政策,Monitoring 在关闭突发事件时是否会发送通知。
    • 对于基于指标的提醒政策,是否启用重复通知,以及这些通知之间的时间间隔。如需了解详情,请参阅为基于指标的提醒政策配置重复通知。

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

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

如果提醒政策包含一个条件,则在满足该条件时会发送通知。如需了解提醒政策包含多个条件时的通知,请参阅包含多个条件的政策以及Monitoring 何时发送通知并创建突发事件。

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

projects/PROJECT_ID/alertPolicies/POLICY_ID

在上述表达式中:

  • PROJECT_ID:项目的标识符。 对于 App Hub 配置,请选择 App Hub 宿主项目或管理项目。
  • POLICY_ID:提醒政策的 ID

API 中的条件类型

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

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

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

基于过滤条件的指标条件

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

如果您使用 MetricAbsence 条件类型,则可以创建仅在所有时序缺失时满足的条件。此条件使用 aggregations 参数将多个时序汇总为单一时序。如需了解详情,请参阅 API 文档中的 MetricAbsence 参考文档。

指标缺失提醒政策要求预先已有数据写入;如需了解详情,请参阅创建指标缺失提醒政策。

如果您想基于预测值接收通知,请将提醒政策配置为使用 MetricThreshold 条件类型并设置 forecastOptions 字段。如果未设置此字段,系统会将测量数据与阈值进行比较。但是,如果设置此字段,则系统会将预测数据与阈值进行比较。如需了解详情,请参阅创建预测指标值提醒政策。

基于 PromQL 的指标条件

PrometheusQueryLanguageCondition 条件使用 Prometheus 查询语言 (PromQL) 查询来选择并操作监控的时序数据。您的条件可以计算指标比率、进行指标比较等。

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

基于比率的提醒条件

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

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

如果您使用 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 创建基于日志的提醒政策。

如何将提醒政策与 App Hub 应用相关联

Google Cloud 会生成信息中心仪表板,以帮助您监控 App Hub 应用。这些信息中心会显示应用的日志和指标数据,以及应用中包含的服务和工作负载等信息。如果提醒政策与应用的服务或工作负载相关联,则这些信息中心也会显示相应政策及其突发事件。如需详细了解应用监控,请参阅查看应用遥测数据。

如需将提醒政策与 App Hub 应用相关联,请将包含以下键的标签附加到您的政策:

  • apphub_application_location
  • apphub_application_id
  • apphub_service_id 或 apphub_workload_id
例如,提醒政策 JSON 表示法的 userLabels 部分可能如下所示:

  "userLabels": {
    "apphub_service_id": "my-service-id",
    "apphub_application_location": "my-app-location",
    "apphub_application_id": "my-app"
  },

准备工作

在针对该 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。 对于 App Hub 配置,请选择 App Hub 宿主项目或管理项目。

创建提醒政策

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

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

每个提醒政策都属于指标范围限定项目。每个项目最多可以包含 2,000 个政策。对于 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 代码。如需详细了解此政策,请参阅变化率政策。

如需了解详情,请查看 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 对象将具有其他字段。 该政策本身有 name、creationRecord 和 mutationRecord 字段。此外,政策中的每个条件也都有一个 name。 这些字段不能在外部修改,因此不必在创建政策时设置这些字段。 创建政策的 JSON 示例里都不包含这些字段,但如果有人在示例创建政策后检索这些政策,则这些字段将出现。

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

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

如需配置重复通知,请向提醒政策的配置添加一个 AlertStrategy 对象,其中包含至少一个 NotificationChannelStrategy 对象。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 对象。

后续步骤