API で通知チャネルを作成して管理する

このドキュメントでは、クライアント ライブラリまたは Google Cloud CLI を使用して通知チャンネルを作成、管理する方法を説明します。どちらも Cloud Monitoring API を呼び出します。Cloud Monitoring は、通知チャンネルを使用して、アラート ポリシーの条件が満たされたときにユーザーまたはユーザーのオンコール チームに通知します。使用可能なチャンネルの種類がいくつかあり、種類ごとに通知チャンネル記述子に記述されています。特定の種類の通知チャネルは、その種類の記述子のインスタンスになっています。アラート ポリシーには、通知経路として使用する通知チャネルへの参照が含まれます。

通知チャネルは、アラート ポリシーで使用する前に存在している必要があります。通知チャネル記述子は提供されますが、通知チャネルは自分で作成する必要があります。

Google Cloud コンソールを使用して通知チャネルを構成するには、通知チャネルの作成と管理をご覧ください。

このドキュメントで使用されているコードサンプルは、例: バックアップと復元で説明しているアラート ポリシー API の例から抽出したものです。

この API について

NotificationChannel リソースでは、通知チャンネルを管理するオペレーションがサポートされています。また、チャンネルの verificationStatus フィールドの管理に関連するオペレーションもサポートしています。

  • 確認コードの送信
  • 検証されたチャネルの検証ステータスを、同じプロジェクトまたは新しいプロジェクトの他の同一のチャネルにコピーするためにコードを生成する
  • 前の 2 つのオペレーションで作成されたコードを使用してチャネルを検証する

詳細については、notificationChannels リファレンス ドキュメントをご覧ください。

準備

Cloud Monitoring API を使用して通知チャネルを表示および構成するために必要な権限を取得するには、プロジェクトに対する Monitoring NotificationChannel 編集者roles/monitoring.notificationChannelEditor)の IAM ロールの付与を管理者に依頼します。 ロールの付与の詳細については、アクセスの管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

Cloud Monitoring のロールの詳細については、Identity and Access Management を使用してアクセスを制御するをご覧ください。

通知チャンネルのタイプを一覧表示する

Monitoring には、多数の組み込み型通知チャネルタイプが用意されています。これらの種類は、それぞれ NotificationChannelDescriptor として記述されています。これらの記述子には type フィールドがあります。このフィールドの値は、そのチャネルの種類のインスタンスを作成するときの ID として機能します。通知チャネルの作成と管理で説明しているように、次のコマンドを使用すると、利用可能なチャネルタイプを取得できます。

$ gcloud beta monitoring channel-descriptors list --format='value(type)'
campfire
email
google_chat
hipchat
pagerduty
pubsub
slack
sms
webhook_basicauth
webhook_tokenauth

目的の通知チャネルがサポートされていない場合は、Pub/Sub への通知の送信に依存するパイプラインの作成を検討してください。Flask を使用する Python の例については、Cloud Monitoring と Cloud Run を使用したカスタム通知の作成をご覧ください。その他の例については、cloud-alerting-notification-forwarding Git リポジトリをご覧ください。

Google Cloud プロジェクト内のすべてのチャンネル記述子を取得するには、notificationChannelDescriptors.list メソッドを使用します。取得した記述子は読み取り専用です。

特定の記述子を探していて、その名前がわかっている場合は、notificationChannelDescriptors.get メソッドを使用するとそのチャネル記述子だけを取得できます。チャネル記述子の名前は、projects/[PROJECT_ID]/notificationChannelDescriptors/[CHANNEL_TYPE] という形式です。[CHANNEL_TYPE] は上記の種類のいずれかとなり、たとえば次のようになります。

projects/[PROJECT_ID]/notificationChannelDescriptors/email

gcloud

Google Cloud プロジェクト内のすべての通知チャンネル記述子を一覧表示するには、gcloud beta monitoring channel-descriptors list コマンドを使用します。

gcloud beta monitoring channel-descriptors list

成功すると、list コマンドは、指定されたプロジェクト内のすべてのチャネル記述子のリストを提供します。たとえば、email チャネル記述子は次のようにリストに表示されます。

    ---
    description: A channel that sends notifications via email.
    displayName: Email
    labels:
    - description: An address to send email.
      key: email_address
    name: projects/[PROJECT_ID]/notificationChannelDescriptors/email
    type: email
    ---

すべてのチャネル記述子に次のフィールドがあります。

  • name: チャネル記述子の完全修飾リソース名
  • type: チャネルのタイプを示す名前の部分
  • displayName: 表示用の type フィールドの説明文
  • description: チャネルの簡単な説明
  • labels: チャネルタイプに固有の一連のフィールド。各チャネルタイプには独自のラベルセットがあります。

チャネルが作成される際に、enabled フィールドの値も指定されます(デフォルト値は true)。

単一のチャネル記述子を一覧表示するには、gcloud beta monitoring channel-descriptors describe を使用し、チャネル記述子の名前を指定します。完全修飾名を指定する必要はありません。たとえば、次のコマンドを実行すると、上記のリストが返されます。

gcloud beta monitoring channel-descriptors describe email

gcloud beta monitoring channel-descriptors describe projects/[PROJECT_ID]/notificationChannelDescriptors/email

詳細については、gcloud beta monitoring channel-descriptors listdescribe のリファレンスをご覧ください。describe コマンドは、API の notificationChannelDescriptors.get メソッドに相当します。

通知チャンネルを作成する

Google Cloud CLI を使用して、JSON ファイルまたは YAML ファイルから Google Cloud プロジェクトの通知チャンネルを作成するか、プログラムで作成できます。

通知チャネルを作成するには、その記述子のフィールドに値を指定します。type など、ほとんどはどの通知チャネル記述子にも対応しています(notificationChannelDescriptors を参照)。

各記述子には一連のラベルが割り当てられます。このセットは記述子によって異なります。特定の記述子のラベルセットを確認するには、通知チャネルの種類を一覧表示するで説明されている gcloud beta monitoring channel-descriptors describe コマンドで記述子を取得します。たとえば、email チャネル記述子を取得すると、1 つのラベルが表示されます。

    labels:
    - description: An address to send email.
      key: email_address

pubsub チャネル記述子には、Pub/Sub トピックを識別する単一のラベルも含まれています。ただし、チャネルには複数のラベルを含めることができます。たとえば、slack チャネル記述子には 2 つのラベルがあります。

    labels:
    - description: A permanent authentication token provided by Slack. This field is obfuscated by returning only a few characters of the key when fetched.
      key: auth_token
    - description: The Slack channel to which to post notifications.
      key: channel_name

webhook_basicauth チャネル記述子を取得すると、いくつかのラベルが表示されます。

    labels:
    - description: The password. The field is obfuscated when the channel is fetched.
      key: password
    - description: The public URL to which to publish the webhook.
      key: url
    - description: The username.
      key: username

プログラムまたはコマンドラインから新しいチャネルを作成する場合、仕様内の type の値は、対応する通知チャネル記述子の type フィールドと一致しなければなりません。必要なラベルキーもチャネル記述子と一致する必要があります。

一部のラベルは、プロバイダとの認証に使用される認証情報に対応しています。チャネルを作成するときに、これらのラベルの値をプロバイダから取得する必要があります。認証情報を取得するには、プロバイダのウェブサイトの API キー生成ページを使用するか、プロバイダとの OAuth ログインフローを行う必要があります。認証情報を取得する方法の詳細は、プロバイダによって異なります。

たとえば、JSON の新しい pubsub 通知チャネルの仕様は次のとおりです。

    {
      "type": "pubsub",
      "displayName": "Notifications",
      "description": "Pub/Sub channel for notifications",
      "labels": {
        "topic": "projects/[PROJECT_ID]/topics/notificationTopic"
      },
    }

type 値(pubsub)と 1 つのラベルキー(topic)が、対応するチャネル記述子の type フィールドと labels.key フィールドに対応しています。

チャネルはデフォルトで有効になっています。非アクティブなチャネルを作成する場合は、フィールド enabled に値 false を指定します。

次の例で、通知チャネルの作成手順を説明します。

gcloud

Google Cloud プロジェクトに通知チャンネルを作成するには、gcloud beta monitoring channels create コマンドを使用します。ファイルからチャネルを読み込むには、--channel-content-from-file フラグを使用してファイルを指定します。

次の例では、新しい Pub/Sub チャネルを pubsub-channel.json ファイルから作成します。

gcloud beta monitoring channels create --channel-content-from-file="pubsub-channel.json"

このコマンドが成功すると、新しいチャネルの名前が戻ります。たとえば、次のようになります。

    Created notification channel [projects/[PROJECT_ID]/notificationChannels/1355376463305411567].

詳しくは、gcloud beta monitoring channels 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)
    {
        try
        {
            bool updated = false;
            Console.WriteLine("Updating channel.\n{0}",
                channel.DisplayName);
            // This field is immutable and it is illegal to specify a
            // non-default value (UNVERIFIED or VERIFIED) in the
            // Create() or Update() operations.
            channel.VerificationStatus = NotificationChannel.Types
                .VerificationStatus.Unspecified;
            if (isSameProject)
                try
                {
                    channelClient.UpdateNotificationChannel(
                        null, channel);
                    updated = true;
                }
                catch (Grpc.Core.RpcException e)
                when (e.Status.StatusCode == StatusCode.NotFound)
                { }
            if (!updated)
            {
                // The channel no longer exists.  Recreate it.
                string oldName = channel.Name;
                channel.Name = null;
                var response = channelClient.CreateNotificationChannel(
                    projectName, channel);
                channelNameMap.Add(oldName, response.Name);
            }
        }
        catch (Exception e)
        {
            // If one failed, continue trying to update the others.
            exceptions.Add(e);
        }
    }
    foreach (AlertPolicy policy in backup.Policies)
    {
    }
    if (exceptions.Count > 0)
    {
        throw new AggregateException(exceptions);
    }
}

Node.js

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

// Creates clients
const alertClient = new monitoring.AlertPolicyServiceClient();
const notificationClient = new monitoring.NotificationChannelServiceClient();

async function replaceChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const alertPolicyId = '123456789012314';
  // const channelIds = [
  //   'channel-1',
  //   'channel-2',
  //   'channel-3',
  // ];

  const notificationChannels = channelIds.map(id =>
    notificationClient.projectNotificationChannelPath(projectId, id)
  );

  for (const channel of notificationChannels) {
    const updateChannelRequest = {
      updateMask: {
        paths: ['enabled'],
      },
      notificationChannel: {
        name: channel,
        enabled: {
          value: true,
        },
      },
    };
    try {
      await notificationClient.updateNotificationChannel(
        updateChannelRequest
      );
    } catch (err) {
      const createChannelRequest = {
        notificationChannel: {
          name: channel,
          notificationChannel: {
            type: 'email',
          },
        },
      };
      const newChannel =
        await notificationClient.createNotificationChannel(
          createChannelRequest
        );
      notificationChannels.push(newChannel);
    }
  }

  const updateAlertPolicyRequest = {
    updateMask: {
      paths: ['notification_channels'],
    },
    alertPolicy: {
      name: alertClient.projectAlertPolicyPath(projectId, alertPolicyId),
      notificationChannels: notificationChannels,
    },
  };
  const [alertPolicy] = await alertClient.updateAlertPolicy(
    updateAlertPolicyRequest
  );
  console.log(`Updated ${alertPolicy.name}.`);
}
replaceChannels();

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 Map<String, String> restoreNotificationChannels(
    String projectId, List<NotificationChannel> channels, boolean isSameProject)
    throws IOException {
  Map<String, String> newChannelNames = Maps.newHashMap();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    for (NotificationChannel channel : channels) {
      // Update channel name if project ID is different.
      boolean channelUpdated = false;
      if (isSameProject) {
        try {
          NotificationChannel updatedChannel =
              client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel);
          newChannelNames.put(channel.getName(), updatedChannel.getName());
          channelUpdated = true;
        } catch (Exception e) {
          channelUpdated = false;
        }
      }
      if (!channelUpdated) {
        NotificationChannel newChannel =
            client.createNotificationChannel(
                ProjectName.of(projectId),
                channel.toBuilder().clearName().clearVerificationStatus().build());
        newChannelNames.put(channel.getName(), newChannel.getName());
      }
    }
  }
  return newChannelNames;
}

PHP

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\CreateNotificationChannelRequest;
use Google\Cloud\Monitoring\V3\NotificationChannel;

/**
 * @param string $projectId Your project ID
 */
function alert_create_channel(string $projectId): void
{
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;

    $channel = new NotificationChannel();
    $channel->setDisplayName('Test Notification Channel');
    $channel->setType('email');
    $channel->setLabels(['email_address' => 'fake@example.com']);
    $createNotificationChannelRequest = (new CreateNotificationChannelRequest())
        ->setName($projectName)
        ->setNotificationChannel($channel);

    $channel = $channelClient->createNotificationChannel($createNotificationChannelRequest);
    printf('Created notification channel %s' . PHP_EOL, $channel->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)

例: Slack 通知チャンネルを作成する

Slack アプリの通知チャンネルを構成する手順は次のとおりです。

  1. Slack アプリを構成します。

    1. Slack アプリをまだ持っていない場合は、Slack リファレンス ドキュメントに従ってアプリを作成し、ワークスペースにインストールします。
    2. chat:writechat:write.public の OAuth スコープを使用して Slack アプリを構成します。
    3. アプリのボットユーザー OAuth トークンをコピーします。
  2. 通知チャンネルの構成を定義するファイルを作成します。auth_token キーに Slack アプリのボットユーザー OAuth トークンの値があるラベルを含めます。次に例を示します。

    {
      "description": "A Slack notification channel",
      "displayName": "Slack",
      "type": "slack",
      "enabled": true,
      "labels": {
        "auth_token": "OAUTH_TOKEN_VALUE",
        "channel_name": "SLACK_CHANNEL_NAME"
      }
    }
    
  3. 次のコマンドを実行して、通知チャンネルを作成します。

    gcloud beta monitoring channels create --channel-content-from-file="FILE_NAME"
    

プロジェクト内の通知チャンネルを一覧表示する

Google Cloud プロジェクト内のすべての通知チャンネルを取得するには、notificationChannels.list メソッドを使用します。このメソッドでは filter オプションと orderBy オプションもサポートされており、結果を絞り込んだり並べ替えたりできます。並べ替えとフィルタリングをご覧ください。

特定のチャネルを探していて、その名前がわかっている場合は、notificationChannels.get メソッドを使用するとそのチャネルだけを取得できます。チャネルの名前は projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID] という形式です。たとえば、次のようになります。

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

チャネルを取得すると、セキュリティ上の理由から、認証トークンや API キーなどの機密値が難読化される可能性があります。既存のチャネルをコピーして新しいチャネルを作成している場合は、難読化された値を修正する必要があります。

gcloud

Google Cloud プロジェクト内のすべての通知チャンネルを一覧表示するには、gcloud beta monitoring channels list コマンドを使用します。

gcloud beta monitoring channels list

成功すると、list コマンドは、指定されたプロジェクト内のすべてのチャネルのリストを提供します。たとえば、上記のコマンドは、次のエントリを含むリストを返します。

    ---
    description: E-mail channel created by gcloud as a test
    displayName: test e-mail channel
    enabled: false
    labels:
      email_address: user@example.com
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: email
    ---
    description: Pub/Sub channel for notifications
    displayName: Notifications
    enabled: true
    labels:
      topic: projects/[PROJECT_ID]/topics/notificationTopic
    name: projects/[PROJECT_ID]/notificationChannels/1355376463305411567
    type: pubsub

単一のチャネルを表示するには、gcloud beta monitoring channels describe を使用し、チャネルの名前を指定します。 たとえば、次のコマンドは、上記のリストに示す Pub/Sub チャネルを返します。

gcloud beta monitoring channels describe projects/[PROJECT_ID]/notificationChannels/1355376463305411567


詳細については、gcloud beta monitoring channels listdescribe のリファレンスをご覧ください。describe コマンドは、API の notificationChannels.get メソッドに相当します。

C#

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

static void ListNotificationChannels(string projectId)
{
    var client = NotificationChannelServiceClient.Create();
    var response = client.ListNotificationChannels(new ProjectName(projectId));
    foreach (NotificationChannel channel in response)
    {
        Console.WriteLine(channel.Name);
        if (channel.DisplayName != null)
        {
            Console.WriteLine(channel.DisplayName);
        }
        Console.WriteLine();
    }
}

Node.js

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

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

async function deleteChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const filter = 'A filter for selecting policies, e.g. description:"cloud"';

  const request = {
    name: client.projectPath(projectId),
    filter,
  };
  const channels = await client.listNotificationChannels(request);
  console.log(channels);
  for (const channel of channels[0]) {
    console.log(`Deleting channel ${channel.displayName}`);
    try {
      await client.deleteNotificationChannel({
        name: channel.name,
      });
    } catch (err) {
      // ignore error
    }
  }
}
deleteChannels();

Go

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

channelClient, err := monitoring.NewNotificationChannelClient(ctx)
if err != nil {
	return err
}
defer channelClient.Close()
channelReq := &monitoringpb.ListNotificationChannelsRequest{
	Name: "projects/" + projectID,
	// Filter:  "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
	// OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.
}
channelIt := channelClient.ListNotificationChannels(ctx, channelReq)
for {
	resp, err := channelIt.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	b.Channels = append(b.Channels, &channel{resp})
}

Java

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

private static List<NotificationChannel> getNotificationChannels(String projectId)
    throws IOException {
  List<NotificationChannel> notificationChannels = Lists.newArrayList();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    ListNotificationChannelsPagedResponse listNotificationChannelsResponse =
        client.listNotificationChannels(ProjectName.of(projectId));
    for (NotificationChannel channel : listNotificationChannelsResponse.iterateAll()) {
      notificationChannels.add(channel);
    }
  }
  return notificationChannels;
}

PHP

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\ListNotificationChannelsRequest;

/**
 * @param string $projectId Your project ID
 */
function alert_list_channels($projectId)
{
    $projectName = 'projects/' . $projectId;
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $listNotificationChannelsRequest = (new ListNotificationChannelsRequest())
        ->setName($projectName);

    $channels = $channelClient->listNotificationChannels($listNotificationChannelsRequest);
    foreach ($channels->iterateAllElements() as $channel) {
        printf('Name: %s (%s)' . PHP_EOL, $channel->getDisplayName(), $channel->getName());
    }
}

Python

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

def list_notification_channels(project_name):
    """List alert notification channels in a project.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
    """

    client = monitoring_v3.NotificationChannelServiceClient()
    channels = client.list_notification_channels(name=project_name)
    print(
        tabulate.tabulate(
            [(channel.name, channel.display_name) for channel in channels],
            ("name", "display_name"),
        )
    )

プロジェクトから通知チャンネルを削除する

通知チャンネルを Google Cloud プロジェクトから削除するには、notificationChannels.delete メソッドを使用し、削除する通知チャンネルの名前を指定します。チャネルの名前は NotificationChannel インスタンス内の name フィールドの値です。displayName フィールドの値ではありません。 チャネルの名前は projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID] という形式です。たとえば、次のようになります。

    projects/[PROJECT_ID]/notificationChannels/1355376463305411567

デフォルトでは、アラート ポリシーによって参照されているチャネルを削除しようとしても、そのチャネルは削除されません。アラート ポリシーからの参照を強制的に削除し、チャネルも削除するには、force オプションを true に設定します。このオプションにより、このチャンネルはすべての参照ポリシーから自動的に削除されます。

gcloud

通知チャネルを削除するには、gcloud beta monitoring channels delete を使用し、削除するチャネルの名前を指定します。たとえば、次のコマンドは、別の使用例で作成した email チャネルを削除します。

gcloud beta monitoring channels delete projects/[PROJECT_ID]/notificationChannels/1355376463305411567

詳細については、gcloud beta monitoring channels delete のリファレンスをご覧ください。

C#

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


using Google.Cloud.Monitoring.V3;
using System;

partial class AlertSnippets
{
    public void DeleteNotificationChannel(
        string channelName = "projects/your-project-id/notificationChannels/123")
    {
        var client = NotificationChannelServiceClient.Create();
        client.DeleteNotificationChannel(
            name: NotificationChannelName.Parse(channelName),
            force: true);
        Console.WriteLine("Deleted {0}.", channelName);
    }
}

Go

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
)

// deleteChannel deletes the given channel. channelName should be of the form
// "projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]".
func deleteChannel(w io.Writer, channelName string) error {
	ctx := context.Background()

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

	req := &monitoringpb.DeleteNotificationChannelRequest{
		Name: channelName,
	}

	if err := client.DeleteNotificationChannel(ctx, req); err != nil {
		return fmt.Errorf("DeleteNotificationChannel: %w", err)
	}

	fmt.Fprintf(w, "Deleted channel %q", channelName)
	return nil
}

Java

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

static void deleteNotificationChannel(String channelName) throws IOException {
  String projectId = System.getProperty("projectId");
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    NotificationChannelName name = NotificationChannelName.of(projectId, channelName);
    client.deleteNotificationChannel(channelName, false);
    System.out.println("Deleted notification channel " + channelName);
  }
}

PHP

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\DeleteNotificationChannelRequest;

/**
 * @param string $projectId Your project ID
 * @param string $channelId
 */
function alert_delete_channel(string $projectId, string $channelId): void
{
    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);
    $channelName = $channelClient->notificationChannelName($projectId, $channelId);
    $deleteNotificationChannelRequest = (new DeleteNotificationChannelRequest())
        ->setName($channelName);

    $channelClient->deleteNotificationChannel($deleteNotificationChannelRequest);
    printf('Deleted notification channel %s' . PHP_EOL, $channelName);
}

Node.js

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

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

async function deleteChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const filter = 'A filter for selecting policies, e.g. description:"cloud"';

  const request = {
    name: client.projectPath(projectId),
    filter,
  };
  const channels = await client.listNotificationChannels(request);
  console.log(channels);
  for (const channel of channels[0]) {
    console.log(`Deleting channel ${channel.displayName}`);
    try {
      await client.deleteNotificationChannel({
        name: channel.name,
      });
    } catch (err) {
      // ignore error
    }
  }
}
deleteChannels();

Python

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

def delete_notification_channels(project_name, channel_ids, force=None):
    """Delete alert notification channels.

    Arguments:
        project_name (str): The Google Cloud Project to use. The project name
            must be in the format - 'projects/<PROJECT_NAME>'.
        channel_ids list(str): List of IDs of notification channels to delete.
        force (bool): If true, the notification channels are deleted regardless
            of its in use by alert policies. If false, channels that are still
            referenced by an existing alerting policy will fail to be deleted.
    """

    channel_client = monitoring_v3.NotificationChannelServiceClient()
    for channel_id in channel_ids:
        channel_name = "{}/notificationChannels/{}".format(project_name, channel_id)
        try:
            channel_client.delete_notification_channel(name=channel_name, force=force)
            print("Channel {} deleted".format(channel_name))
        except ValueError:
            print("The parameters are invalid")
        except Exception as e:
            print("API call failed: {}".format(e))

通知チャンネルに変更を加える

通知チャネルに変更を加えるには、notificationChannels.patch メソッド(REST API 内)を使用します。他の API の実装と Google Cloud CLI では、patch ではなく、この update を呼び出します。

更新オペレーションは、既存のチャネルを完全に置き換えることも、フィールドのサブセットを変更することもできます。たとえば、チャネルを有効または無効にすることができます。チャネルを無効にすると、チャネルへの通知の配信ができなくなります。変更が一時的な場合、チャネルを参照するアラート ポリシーからチャネルを削除するのではなく、通常はチャネルを無効にすることをおすすめします。

gcloud

無効になっている通知チャネルを有効にするには、gcloud beta monitoring channels update コマンドを使用し、--enabled フラグを指定します。次のコマンドで、前の例で(無効状態で)作成した email 通知チャネルを有効にします。

gcloud beta monitoring channels update projects/[PROJECT_ID]/notificationChannels/1355376463305411567 --enabled

ポリシーを無効にする場合にも同じコマンドを使用しますが、--no-enabled フラグを指定します。詳細については、gcloud beta monitoring channels update リファレンスをご覧ください。update コマンドは、REST API の notificationChannels.patch メソッドに相当します。

C#

Monitoring への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using System;

partial class AlertSnippets
{
    public NotificationChannel EnableNotificationChannel(
        string channelName = "projects/your-project-id/notificationChannels/123")
    {
        var client = NotificationChannelServiceClient.Create();
        NotificationChannel channel = new NotificationChannel();
        channel.Enabled = true;
        channel.Name = channelName;
        var fieldMask = new FieldMask { Paths = { "enabled" } };
        channel = client.UpdateNotificationChannel(
            updateMask: fieldMask,
            notificationChannel: channel);
        Console.WriteLine("Enabled {0}.", channel.Name);
        return channel;
    }
}

Go

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"github.com/golang/protobuf/ptypes/wrappers"
	"google.golang.org/genproto/protobuf/field_mask"
)

// enableChannel enables the given channel. channelName should be of the form
// "projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID]".
func enableChannel(w io.Writer, channelName string) error {
	ctx := context.Background()

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

	req := &monitoringpb.UpdateNotificationChannelRequest{
		UpdateMask: &field_mask.FieldMask{Paths: []string{"enabled"}},
		NotificationChannel: &monitoringpb.NotificationChannel{
			Name:    channelName,
			Enabled: &wrappers.BoolValue{Value: true},
		},
	}

	if _, err := client.UpdateNotificationChannel(ctx, req); err != nil {
		return fmt.Errorf("EnableNotificationChannel: %w", err)
	}

	fmt.Fprintf(w, "Enabled channel %q", channelName)
	return nil
}

Node.js

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

// Creates clients
const alertClient = new monitoring.AlertPolicyServiceClient();
const notificationClient = new monitoring.NotificationChannelServiceClient();

async function replaceChannels() {
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const alertPolicyId = '123456789012314';
  // const channelIds = [
  //   'channel-1',
  //   'channel-2',
  //   'channel-3',
  // ];

  const notificationChannels = channelIds.map(id =>
    notificationClient.projectNotificationChannelPath(projectId, id)
  );

  for (const channel of notificationChannels) {
    const updateChannelRequest = {
      updateMask: {
        paths: ['enabled'],
      },
      notificationChannel: {
        name: channel,
        enabled: {
          value: true,
        },
      },
    };
    try {
      await notificationClient.updateNotificationChannel(
        updateChannelRequest
      );
    } catch (err) {
      const createChannelRequest = {
        notificationChannel: {
          name: channel,
          notificationChannel: {
            type: 'email',
          },
        },
      };
      const newChannel =
        await notificationClient.createNotificationChannel(
          createChannelRequest
        );
      notificationChannels.push(newChannel);
    }
  }

  const updateAlertPolicyRequest = {
    updateMask: {
      paths: ['notification_channels'],
    },
    alertPolicy: {
      name: alertClient.projectAlertPolicyPath(projectId, alertPolicyId),
      notificationChannels: notificationChannels,
    },
  };
  const [alertPolicy] = await alertClient.updateAlertPolicy(
    updateAlertPolicyRequest
  );
  console.log(`Updated ${alertPolicy.name}.`);
}
replaceChannels();

Java

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

private static Map<String, String> restoreNotificationChannels(
    String projectId, List<NotificationChannel> channels, boolean isSameProject)
    throws IOException {
  Map<String, String> newChannelNames = Maps.newHashMap();
  try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
    for (NotificationChannel channel : channels) {
      // Update channel name if project ID is different.
      boolean channelUpdated = false;
      if (isSameProject) {
        try {
          NotificationChannel updatedChannel =
              client.updateNotificationChannel(NOTIFICATION_CHANNEL_UPDATE_MASK, channel);
          newChannelNames.put(channel.getName(), updatedChannel.getName());
          channelUpdated = true;
        } catch (Exception e) {
          channelUpdated = false;
        }
      }
      if (!channelUpdated) {
        NotificationChannel newChannel =
            client.createNotificationChannel(
                ProjectName.of(projectId),
                channel.toBuilder().clearName().clearVerificationStatus().build());
        newChannelNames.put(channel.getName(), newChannel.getName());
      }
    }
  }
  return newChannelNames;
}

PHP

Monitoring で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\ApiCore\ApiException;
use Google\Cloud\Monitoring\V3\AlertPolicy;
use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient;
use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient;
use Google\Cloud\Monitoring\V3\CreateAlertPolicyRequest;
use Google\Cloud\Monitoring\V3\CreateNotificationChannelRequest;
use Google\Cloud\Monitoring\V3\NotificationChannel;
use Google\Cloud\Monitoring\V3\NotificationChannel\VerificationStatus;
use Google\Cloud\Monitoring\V3\UpdateAlertPolicyRequest;
use Google\Cloud\Monitoring\V3\UpdateNotificationChannelRequest;

/**
 * @param string $projectId Your project ID
 */
function alert_restore_policies(string $projectId): void
{
    $alertClient = new AlertPolicyServiceClient([
        'projectId' => $projectId,
    ]);

    $channelClient = new NotificationChannelServiceClient([
        'projectId' => $projectId,
    ]);

    print('Loading alert policies and notification channels from backup.json.' . PHP_EOL);
    $projectName = 'projects/' . $projectId;
    $record = json_decode((string) file_get_contents('backup.json'), true);
    $isSameProject = $projectName == $record['project_name'];

    # Convert dicts to AlertPolicies.
    $policies = [];
    foreach ($record['policies'] as $policyArray) {
        $policy = new AlertPolicy();
        $policy->mergeFromJsonString((string) json_encode($policyArray));
        $policies[] = $policy;
    }

    # Convert dicts to NotificationChannels
    $channels = [];
    foreach (array_filter($record['channels']) as $channelArray) {
        $channel = new NotificationChannel();
        $channel->mergeFromJsonString((string) json_encode($channelArray));
        $channels[] = $channel;
    }

    # Restore the channels.
    $channelNameMap = [];
    foreach ($channels as $channel) {
        $updated = false;
        printf('Updating channel %s' . PHP_EOL, $channel->getDisplayName());

        # This field is immutable and it is illegal to specify a
        # non-default value (UNVERIFIED or VERIFIED) in the
        # Create() or Update() operations.
        $channel->setVerificationStatus(
            VerificationStatus::VERIFICATION_STATUS_UNSPECIFIED
        );

        if ($isSameProject) {
            try {
                $updateNotificationChannelRequest = (new UpdateNotificationChannelRequest())
                    ->setNotificationChannel($channel);
                $channelClient->updateNotificationChannel($updateNotificationChannelRequest);
                $updated = true;
            } catch (ApiException $e) {
                # The channel was deleted.  Create it below.
                if ($e->getStatus() !== 'NOT_FOUND') {
                    throw $e;
                }
            }
        }

        if (!$updated) {
            # The channel no longer exists.  Recreate it.
            $oldName = $channel->getName();
            $channel->setName('');
            $createNotificationChannelRequest = (new CreateNotificationChannelRequest())
                ->setName($projectName)
                ->setNotificationChannel($channel);
            $newChannel = $channelClient->createNotificationChannel($createNotificationChannelRequest);
            $channelNameMap[$oldName] = $newChannel->getName();
        }
    }

    # Restore the alerts
    foreach ($policies as $policy) {
        printf('Updating policy %s' . PHP_EOL, $policy->getDisplayName());
        # These two fields cannot be set directly, so clear them.
        $policy->clearCreationRecord();
        $policy->clearMutationRecord();

        $notificationChannels = $policy->getNotificationChannels();

        # Update old channel names with new channel names.
        foreach ($notificationChannels as $i => $channel) {
            if (isset($channelNameMap[$channel])) {
                $notificationChannels[$i] = $channelNameMap[$channel];
            }
        }

        $updated = false;
        if ($isSameProject) {
            try {
                $updateAlertPolicyRequest = (new UpdateAlertPolicyRequest())
                    ->setAlertPolicy($policy);
                $alertClient->updateAlertPolicy($updateAlertPolicyRequest);
                $updated = true;
            } catch (ApiException $e) {
                # The policy was deleted.  Create it below.
                if ($e->getStatus() !== 'NOT_FOUND') {
                    throw $e;
                }
            }
        }

        if (!$updated) {
            # The policy no longer exists.  Recreate it.
            $oldName = $policy->getName();
            $policy->setName('');
            foreach ($policy->getConditions() as $condition) {
                $condition->setName('');
            }
            $createAlertPolicyRequest = (new CreateAlertPolicyRequest())
                ->setName($projectName)
                ->setAlertPolicy($policy);
            $policy = $alertClient->createAlertPolicy($createAlertPolicyRequest);
        }
        printf('Updated %s' . PHP_EOL, $policy->getName());
    }
    print('Restored alert policies and notification channels from backup.json.');
}

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)

通知チャンネルのログを表示する

ログ エクスプローラを使用して、通知チャネルのエラーを表示できます。

  1. Google Cloud コンソールのナビゲーション パネルで、[Logging] を選択してから、[ログ エクスプローラ] を選択します。

    [ログ エクスプローラ] に移動

  2. クエリを入力して実行します。通知チャネルエラーに固有のクエリについては、Cloud Monitoring のクエリをご覧ください。