管理運作時間檢查

本文說明如何使用Google Cloud 控制台、Google Cloud CLI、Cloud Monitoring API 和用戶端程式庫,管理正常運作時間檢查。

這項功能僅支援 Google Cloud 專案。 如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

事前準備

在儲存運作時間檢查的 Google Cloud 專案中完成下列步驟:

  • Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

      In the Google Cloud console, activate Cloud Shell.

      Activate Cloud Shell

      At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

      C#

      如要在本機開發環境中使用本頁的 .NET 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Go

      如要在本機開發環境中使用本頁的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Java

      如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Node.js

      如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      PHP

      如要在本機開發環境中使用本頁的 PHP 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Python

      如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Ruby

      如要在本機開發環境中使用本頁的 Ruby 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. If you're using a local shell, then create local authentication credentials for your user account:

        gcloud auth application-default login

        You don't need to do this if you're using Cloud Shell.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      REST

      如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

列出所有運作時間檢查

控制台

  1. 前往 Google Cloud 控制台的「運作時間檢查」頁面:

    前往「Uptime checks」(運作時間檢查)

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

    以下範例顯示「運作時間檢查」頁面:

    運作時間檢查總覽範例 (已套用篩選器)。

  2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。

  3. (選用) 如要限制列出的正常運作時間檢查,請新增篩選條件。

    每個篩選條件都包含名稱和值。您可以將值設為與運作時間檢查名稱完全相符,或部分相符。比對作業不會區分大小寫。舉例來說,如要列出名稱包含 default 的所有運作時間檢查,請執行下列操作:

    • 按一下「篩選表格」,然後選取「顯示名稱」
    • 輸入 default,然後按下 Return 鍵。

    如有多個篩選器,系統會自動以邏輯 AND 聯集篩選器合併,除非您插入 OR 篩選器。上一個範例使用 OR 篩選器,因此如果正常運作時間檢查的名稱符合 defaultTesting check,就會列出該檢查。

gcloud

如要列出運作時間檢查和綜合監控,請執行 gcloud monitoring uptime list-configs 指令:

gcloud monitoring uptime list-configs --project=PROJECT_ID

執行上一個指令前,請先取代下列項目:

  • PROJECT_ID:專案的 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

傳回的資料包括:

  • 名稱和顯示名稱。
  • 檢查 ID。
  • 受監控資源。
  • 檢查之間的時間間隔。

您可以設定 Google Cloud CLI 指令,篩選及排序結果。

REST

如要列出運作時間檢查和綜合監控,請呼叫 projects.uptimeCheckConfigs.list 方法。請指定以下參數:

  • 父項:必填。列出運作時間檢查的專案。 如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。這個欄位的格式如下:

    projects/PROJECT_ID
    

C#

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

public static object ListUptimeCheckConfigs(string projectId)
{
    var client = UptimeCheckServiceClient.Create();
    var configs = client.ListUptimeCheckConfigs(new ProjectName(projectId));
    foreach (UptimeCheckConfig config in configs)
    {
        Console.WriteLine(config.Name);
    }
    return 0;
}

Java

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

private static void listUptimeChecks(String projectId) throws IOException {
  ListUptimeCheckConfigsRequest request =
      ListUptimeCheckConfigsRequest.newBuilder().setParent(ProjectName.format(projectId)).build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request);
    for (UptimeCheckConfig config : response.iterateAll()) {
      System.out.println(config.getDisplayName());
    }
  } catch (Exception e) {
    usage("Exception listing uptime checks: " + e.toString());
    throw e;
  }
}

Go

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// list is an example of listing the uptime checks in projectID.
func list(w io.Writer, projectID string) error {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	req := &monitoringpb.ListUptimeCheckConfigsRequest{
		Parent: "projects/" + projectID,
	}
	it := client.ListUptimeCheckConfigs(ctx, req)
	for {
		config, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListUptimeCheckConfigs: %w", err)
		}
		fmt.Fprintln(w, config)
	}
	fmt.Fprintln(w, "Done listing uptime checks")
	return nil
}

Node.js

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';

const request = {
  parent: client.projectPath(projectId),
};

// Retrieves an uptime check config
const [uptimeCheckConfigs] = await client.listUptimeCheckConfigs(request);

uptimeCheckConfigs.forEach(uptimeCheckConfig => {
  console.log(`ID: ${uptimeCheckConfig.name}`);
  console.log(`  Display Name: ${uptimeCheckConfig.displayName}`);
  console.log('  Resource: %j', uptimeCheckConfig.monitoredResource);
  console.log('  Period: %j', uptimeCheckConfig.period);
  console.log('  Timeout: %j', uptimeCheckConfig.timeout);
  console.log(`  Check type: ${uptimeCheckConfig.check_request_type}`);
  console.log(
    '  Check: %j',
    uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck
  );
  console.log(
    `  Content matchers: ${uptimeCheckConfig.contentMatchers
      .map(matcher => matcher.content)
      .join(', ')}`
  );
  console.log(`  Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`);
});

PHP

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\ListUptimeCheckConfigsRequest;

/**
 * Example:
 * ```
 * list_uptime_checks($projectId);
 * ```
 */
function list_uptime_checks(string $projectId): void
{
    $projectName = 'projects/' . $projectId;
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $listUptimeCheckConfigsRequest = (new ListUptimeCheckConfigsRequest())
        ->setParent($projectName);

    $pages = $uptimeCheckClient->listUptimeCheckConfigs($listUptimeCheckConfigsRequest);

    foreach ($pages->iteratePages() as $page) {
        foreach ($page as $uptimeCheck) {
            print($uptimeCheck->getName() . PHP_EOL);
        }
    }
}

Python

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def list_uptime_check_configs(project_id: str) -> pagers.ListUptimeCheckConfigsPager:
    """Gets all uptime checks defined in the Google Cloud project

    Args:
        project_id: Google Cloud project id

    Returns:
        A list of configurations.
        Iterating over this object will yield results and resolve additional pages automatically.
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    configs = client.list_uptime_check_configs(request={"parent": project_id})

    for config in configs:
        pprint.pprint(config)
    return configs

Ruby

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

def list_uptime_check_configs project_id
  client = Google::Cloud::Monitoring.uptime_check_service
  project_name = client.project_path project: project_id
  configs = client.list_uptime_check_configs parent: project_name

  configs.each { |config| puts config.name }
end

查看運作時間檢查的詳細資料

控制台

  1. 前往 Google Cloud 控制台的「運作時間檢查」頁面:

    前往「Uptime checks」(運作時間檢查)

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

  2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。
  3. 找出要查看的運作時間檢查,然後按一下其名稱。

    下方的螢幕截圖顯示名稱為「Testing check」的運作時間檢查詳細資料:

    運作時間檢查詳細資料頁面範例。

    「正常運作時間詳細資料」頁面包含下列資訊:

    • 選取的時間間隔。預設間隔為 1 小時
    • 運作時間檢查的名稱。在範例中,名稱為「Testing check」
    • 您為運作時間檢查新增的標籤。
    • 正常運作時間百分比和平均延遲時間。「運作時間百分比」值是以 (S/T)*100 計算的百分比,其中 S 是所有位置的成功檢查回應數;T 是所有位置的檢查回應總數。如果是群組檢查,則 ST 的值會是當下所有群組成員的加總。

      舉例來說,如果從所有地區執行每分鐘一次的正常運作時間檢查,在 25 分鐘內,6 個位置各會發出 25 個要求,總共 150 個要求。如果資訊主頁回報的正常運作時間為 83.3%,則表示 150 個要求中有 125 個成功。

    • 「通過的檢查」和「運作時間檢查延遲」窗格會以圖形顯示通過的檢查次數,以及每次檢查的延遲時間 (以時間為函式)。

    • 「目前狀態」窗格會顯示最近一次檢查的狀態。 如果區域旁邊顯示綠色圓圈和勾號,表示該區域的檢查上次執行成功;如果顯示紅色圓圈和 X,則表示失敗。如果您已啟用運作時間檢查失敗情形記錄,窗格中會顯示「查看記錄」連結。

    • 「Configuration」(設定) 窗格會顯示運作時間檢查的設定。 這項資料會在建立運作時間檢查時指派。 「檢查 ID」值對應於 API 呼叫中的 CHECK_ID 值。

    • 「快訊政策」窗格會列出相關聯的快訊政策資訊。在範例資訊主頁中,已設定一項快訊政策。

gcloud

如要列出正常運作時間檢查或綜合監控的詳細資料,請執行 gcloud monitoring uptime describe 指令:

gcloud monitoring uptime describe CHECK_ID --project=PROJECT_ID

執行上一個指令前,請先取代下列項目:

  • PROJECT_ID:專案的 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。
  • CHECK_ID:運作時間檢查或綜合監控的 ID。執行 gcloud monitoring uptime list-configs 指令並檢查 name 欄位,即可找出 ID。詳情請參閱找出運作時間檢查的專屬 ID

運作時間檢查傳回的資料包括:

  • 名稱和顯示名稱。
  • 檢查 ID。
  • 受監控資源。
  • 檢查之間的時間間隔。

REST

如要列出運作時間檢查或綜合監控的詳細資料,請呼叫 projects.uptimeCheckConfigs.get 方法。請指定以下參數:

  • 名稱:運作時間檢查設定的完整名稱。

    projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID
    

    在上述運算式中:

    • PROJECT_ID 是儲存運作時間檢查的專案。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

    • CHECK_ID 是運作時間檢查或合成監控項的 ID。詳情請參閱找出運作時間檢查的專屬 ID

C#

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

public static object GetUptimeCheckConfig(string configName)
{
    var client = UptimeCheckServiceClient.Create();
    UptimeCheckConfig config = client.GetUptimeCheckConfig(configName);
    if (config == null)
    {
        Console.Error.WriteLine(
            "No configuration found with the name {0}", configName);
        return -1;
    }
    Console.WriteLine("Name: {0}", config.Name);
    Console.WriteLine("Display Name: {0}", config.DisplayName);
    Console.WriteLine("Http Path: {0}", config.HttpCheck.Path);
    return 0;
}

Java

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

private static void getUptimeCheckConfig(String checkName) throws IOException {
  // Create UptimeCheckServiceSettings instance for add retry mechanism
  UptimeCheckServiceSettings.Builder uptimeCheckServiceSettingsBuilder =
      UptimeCheckServiceSettings.newBuilder();
  uptimeCheckServiceSettingsBuilder
      .getUptimeCheckConfigSettings()
      .setRetrySettings(
          uptimeCheckServiceSettingsBuilder
              .getUptimeCheckConfigSettings()
              .getRetrySettings()
              .toBuilder()
              .setInitialRetryDelay(org.threeten.bp.Duration.ofMillis(100L))
              .setRetryDelayMultiplier(1.3)
              .setMaxRetryDelay(MAX_RECONNECT_BACKOFF_TIME)
              .setInitialRpcTimeout(MAX_RECONNECT_BACKOFF_TIME)
              .setRpcTimeoutMultiplier(1.0)
              .setMaxRpcTimeout(MAX_RECONNECT_BACKOFF_TIME)
              .setTotalTimeout(MAX_RECONNECT_BACKOFF_TIME)
              .setMaxAttempts(6)
              .build());
  UptimeCheckServiceSettings uptimeCheckServiceSettings =
      uptimeCheckServiceSettingsBuilder.build();

  // create UptimeCheckServiceClient with retry setting
  try (UptimeCheckServiceClient client =
      UptimeCheckServiceClient.create(uptimeCheckServiceSettings)) {
    UptimeCheckConfig config = client.getUptimeCheckConfig(checkName);
    if (config != null) {
      System.out.println(config.toString());
    } else {
      System.out.println("No uptime check config found with ID " + checkName);
    }
  } catch (Exception e) {
    usage("Exception getting uptime check: " + e.toString());
    throw e;
  }
}

Go

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// get is an example of getting an uptime check. resourceName should be
// of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
func get(w io.Writer, resourceName string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	req := &monitoringpb.GetUptimeCheckConfigRequest{
		Name: resourceName,
	}
	config, err := client.GetUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("GetUptimeCheckConfig: %w", err)
	}
	fmt.Fprintf(w, "Config: %v", config)
	return config, nil
}

Node.js

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID';

const request = {
  // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check
  name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

console.log(`Retrieving ${request.name}`);

// Retrieves an uptime check config
const [uptimeCheckConfig] = await client.getUptimeCheckConfig(request);
console.log(`ID: ${uptimeCheckConfig.name}`);
console.log(`Display Name: ${uptimeCheckConfig.displayName}`);
console.log('Resource: %j', uptimeCheckConfig.monitoredResource);
console.log('Period: %j', uptimeCheckConfig.period);
console.log('Timeout: %j', uptimeCheckConfig.timeout);
console.log(`Check type: ${uptimeCheckConfig.check_request_type}`);
console.log(
  'Check: %j',
  uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck
);
console.log(
  `Content matchers: ${uptimeCheckConfig.contentMatchers
    .map(matcher => matcher.content)
    .join(', ')}`
);
console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`);

PHP

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\GetUptimeCheckConfigRequest;

/**
 * Example:
 * ```
 * get_uptime_check($projectId, $configName);
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $configName
 */
function get_uptime_check($projectId, $configName)
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $getUptimeCheckConfigRequest = (new GetUptimeCheckConfigRequest())
        ->setName($configName);

    $uptimeCheck = $uptimeCheckClient->getUptimeCheckConfig($getUptimeCheckConfigRequest);

    print('Retrieved an uptime check:' . PHP_EOL);
    print($uptimeCheck->serializeToJsonString() . PHP_EOL);
}

Python

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def get_uptime_check_config(config_name: str) -> uptime.UptimeCheckConfig:
    """Reads the uptime check configuration

    Args:
        config_name: Uptime check configuration identity

    Returns:
        A structure that describes the updated uptime check
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(request={"name": config_name})
    pprint.pprint(config)
    return config

Ruby

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

def get_uptime_check_config config_name
  client = Google::Cloud::Monitoring.uptime_check_service
  config = client.get_uptime_check_config name: config_name
  pp config.to_h
  config
end

編輯運作時間檢查

您可以修改運作時間檢查的部分欄位。舉例來說,您可能希望檢查更頻繁地發生,或是想增加與驗證回應相關的逾時。不過,如果運作時間檢查設定的通訊協定、資源類型或資源有誤,請刪除目前的運作時間檢查,然後建立新的檢查。

如要瞭解如何編輯監控運作時間檢查的快訊政策,請參閱下列文件:

如要編輯公開運作時間檢查,請使用下列任一分頁中的程序。如要編輯私人正常運作時間檢查,請使用「控制台」或「API」分頁:

控制台

  1. 前往 Google Cloud 控制台的「運作時間檢查」頁面:

    前往「Uptime checks」(運作時間檢查)

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

  2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。
  3. 找出要編輯的運作時間檢查,然後執行下列其中一項操作:

    • 按一下「更多」圖示 ,然後選取「編輯」
    • 查看正常運作時間檢查詳細資料,然後按一下「編輯」
  4. 視需要變更欄位的值。您無法修改所有欄位。如果檢查的自訂標頭值為隱藏狀態,即表示您無法查看這些值。

  5. 如要確認檢查狀態,請按一下「測試」。如果測試失敗,請參閱「檢查失敗」瞭解可能原因。

  6. 按一下 [儲存]

gcloud

如要修改運作時間檢查或綜合監控,請執行 gcloud monitoring uptime update 指令:

gcloud monitoring uptime update CHECK_ID OPTIONAL_FLAGS --project=PROJECT_ID

執行上一個指令前,請先取代下列項目:

  • PROJECT_ID:專案的 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。
  • CHECK_ID:運作時間檢查或綜合監控的 ID。執行 gcloud monitoring uptime list-configs 指令並檢查 name 欄位,即可找出 ID。詳情請參閱找出運作時間檢查的專屬 ID

您也必須定義要修改的欄位。

舉例來說,如要將運作時間檢查的週期設為 10 分鐘,請執行下列指令:

gcloud monitoring uptime update CHECK_ID --period=10

REST

呼叫 projects.uptimeCheckConfigs.patch 方法。如下設定方法的參數:

  • uptimeCheckConfig.name:必填。這是 REST 網址的一部分。這是要編輯的運作時間檢查的資源名稱:

    projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID
    

    在上述運算式中:

    • PROJECT_ID 是儲存運作時間檢查的專案。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

    • CHECK_ID 是運作時間檢查或合成監控項的 ID。詳情請參閱找出運作時間檢查的專屬 ID

  • updateMask:選填。這是查詢參數: ?updateMask=[FIELD_LIST][FIELD_LIST]UptimeCheckConfig 物件中應進行變更的逗號分隔欄位清單。例如:

    "resource.type,httpCheck.path"
    
  • 要求主體必須包含 UptimeCheckConfig 與新的欄位值。

如果設定了 updateMask,則只有 updateMask 中列出的欄位會取代現有設定中的對應欄位。如果欄位有子欄位,且欄位列於欄位遮罩中,但沒有任何一個子欄位列於欄位遮罩中,則該欄位的所有子欄位都會取代對應欄位。

如果未設定 updateMask,則要求主體中的設定會取代整個現有設定。

patch 方法會針對已更改的設定傳回 UptimeCheckConfig 物件。

C#

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

public static object UpdateUptimeCheck(string configName,
    string newHttpPath, string newDisplayName)
{
    var client = UptimeCheckServiceClient.Create();
    var config = client.GetUptimeCheckConfig(configName);
    var fieldMask = new FieldMask();
    if (newDisplayName != null)
    {
        config.DisplayName = newDisplayName;
        fieldMask.Paths.Add("display_name");
    }
    if (newHttpPath != null)
    {
        config.HttpCheck.Path = newHttpPath;
        fieldMask.Paths.Add("http_check.path");
    }
    client.UpdateUptimeCheckConfig(config);
    return 0;
}

Java

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

private static void updateUptimeCheck(String checkName, String hostName, String pathName)
    throws IOException {

  UpdateUptimeCheckConfigRequest request =
      UpdateUptimeCheckConfigRequest.newBuilder()
          .setUpdateMask(FieldMask.newBuilder().addPaths("http_check.path"))
          .setUptimeCheckConfig(
              UptimeCheckConfig.newBuilder()
                  .setName(checkName)
                  .setMonitoredResource(
                      MonitoredResource.newBuilder()
                          .setType("uptime_url")
                          .putLabels("host", hostName))
                  .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
                  .setTimeout(Duration.newBuilder().setSeconds(10))
                  .setPeriod(Duration.newBuilder().setSeconds(300)))
          .build();
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    UptimeCheckConfig config = client.updateUptimeCheckConfig(request);
    System.out.println("Uptime check updated: \n" + config.toString());
  } catch (Exception e) {
    usage("Exception updating uptime check: " + e.toString());
    throw e;
  }
}

Go

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// update is an example of updating an uptime check. resourceName should be
// of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
func update(w io.Writer, resourceName, displayName, httpCheckPath string) (*monitoringpb.UptimeCheckConfig, error) {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	getReq := &monitoringpb.GetUptimeCheckConfigRequest{
		Name: resourceName,
	}
	config, err := client.GetUptimeCheckConfig(ctx, getReq)
	if err != nil {
		return nil, fmt.Errorf("GetUptimeCheckConfig: %w", err)
	}
	config.DisplayName = displayName
	config.GetHttpCheck().Path = httpCheckPath
	req := &monitoringpb.UpdateUptimeCheckConfigRequest{
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"display_name", "http_check.path"},
		},
		UptimeCheckConfig: config,
	}
	config, err = client.UpdateUptimeCheckConfig(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("UpdateUptimeCheckConfig: %w", err)
	}
	fmt.Fprintf(w, "Successfully updated %v", resourceName)
	return config, nil
}

Node.js

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID';
// const displayName = 'A New Display Name';
// const path = '/some/path';

const request = {
  // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check
  name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

console.log(`Updating ${request.name} to ${displayName}`);

// Updates the display name and path on an uptime check config
request.uptimeCheckConfig = {
  name: request.name,
  displayName: displayName,
  httpCheck: {
    path: path,
  },
};

request.updateMask = {
  paths: ['display_name', 'http_check.path'],
};

const [response] = await client.updateUptimeCheckConfig(request);
console.log(`${response.name} config updated.`);

PHP

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\GetUptimeCheckConfigRequest;
use Google\Cloud\Monitoring\V3\UpdateUptimeCheckConfigRequest;
use Google\Protobuf\FieldMask;

/**
 * Example:
 * ```
 * update_uptime_checks($projectId);
 * ```
 */
function update_uptime_checks(
    string $projectId,
    string $configName,
    string $newDisplayName = null,
    string $newHttpCheckPath = null
): void {
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $getUptimeCheckConfigRequest = (new GetUptimeCheckConfigRequest())
        ->setName($configName);

    $uptimeCheck = $uptimeCheckClient->getUptimeCheckConfig($getUptimeCheckConfigRequest);
    $fieldMask = new FieldMask();
    if ($newDisplayName) {
        $fieldMask->getPaths()[] = 'display_name';
        $uptimeCheck->setDisplayName($newDisplayName);
    }
    if ($newHttpCheckPath) {
        $paths = $fieldMask->getPaths()[] = 'http_check.path';
        $uptimeCheck->getHttpCheck()->setPath($newHttpCheckPath);
    }
    $updateUptimeCheckConfigRequest = (new UpdateUptimeCheckConfigRequest())
        ->setUptimeCheckConfig($uptimeCheck)
        ->setUpdateMask($fieldMask);

    $uptimeCheckClient->updateUptimeCheckConfig($updateUptimeCheckConfigRequest);

    print($uptimeCheck->serializeToString() . PHP_EOL);
}

Python

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def update_uptime_check_config(
    config_name: str, new_display_name: str = None, new_http_check_path: str = None
) -> uptime.UptimeCheckConfig:
    """Creates a new uptime check configuration

    Args:
        config_name: Uptime check configuration identity
        new_display_name: A new human friendly name of the configuration
        new_http_check_path: A new HTTP endpoint of the configuration

    Returns:
        A structure that describes the updated uptime check
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    config = client.get_uptime_check_config(request={"name": config_name})
    field_mask = field_mask_pb2.FieldMask()
    if new_display_name:
        field_mask.paths.append("display_name")
        config.display_name = new_display_name
    if new_http_check_path:
        field_mask.paths.append("http_check.path")
        config.http_check.path = new_http_check_path
    changed_config = client.update_uptime_check_config(
        request={"uptime_check_config": config, "update_mask": field_mask}
    )
    pprint.pprint(changed_config)
    return changed_config

Ruby

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

def update_uptime_check_config config_name:         nil,
                               new_display_name:    nil,
                               new_http_check_path: nil
  client = Google::Cloud::Monitoring.uptime_check_service
  config = { name: config_name }
  field_mask = { paths: [] }
  unless new_display_name.to_s.empty?
    field_mask[:paths].push "display_name"
    config[:display_name] = new_display_name
  end
  unless new_http_check_path.to_s.empty?
    field_mask[:paths].push "http_check.path"
    config[:http_check] = { path: new_http_check_path }
  end
  client.update_uptime_check_config uptime_check_config: config,
                                    update_mask:         field_mask
end

在您看見新的運作時間檢查結果之前,可能會有長達 5 分鐘的延遲。在該期間,先前運作時間檢查的結果會顯示在資訊主頁中,並在快訊政策中使用。

刪除運作時間檢查

建議您在關閉服務或資源時,刪除運作時間檢查。

如要刪除運作時間檢查,請執行下列操作:

控制台

  1. 前往 Google Cloud 控制台的「運作時間檢查」頁面:

    前往「Uptime checks」(運作時間檢查)

    如果您是使用搜尋列尋找這個頁面,請選取子標題為「Monitoring」的結果

  2. 在 Google Cloud 控制台的工具列中,選取您的 Google Cloud 專案。如為「App Hub」設定,請選取 App Hub 主機專案或已啟用應用程式的資料夾管理專案。
  3. 找出要編輯的運作時間檢查,然後執行下列其中一項操作:

    • 按一下「更多」圖示 ,然後選取「刪除」
    • 查看運作時間檢查詳細資料,然後按一下「Delete」(刪除)

gcloud

如要刪除運作時間檢查或合成監控,請執行 gcloud monitoring uptime delete 指令:

gcloud monitoring uptime delete CHECK_ID --project=PROJECT_ID

執行上一個指令前,請先取代下列項目:

  • PROJECT_ID:專案的 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。
  • CHECK_ID:運作時間檢查或綜合監控的 ID。執行 gcloud monitoring uptime list-configs 指令並檢查 name 欄位,即可找出 ID。詳情請參閱找出運作時間檢查的專屬 ID

REST

如要刪除運作時間檢查或合成監控項,請呼叫 projects.uptimeCheckConfigs.delete 方法。如下填寫參數:

  • 名稱:必填。這是要刪除運作時間檢查設定的資源名稱:

    projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID
    

    在上述運算式中:

    • PROJECT_ID 是儲存運作時間檢查的專案。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

    • CHECK_ID 是運作時間檢查或合成監控項的 ID。詳情請參閱找出運作時間檢查的專屬 ID

C#

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

public static object DeleteUptimeCheckConfig(string configName)
{
    var client = UptimeCheckServiceClient.Create();
    client.DeleteUptimeCheckConfig(configName);
    Console.WriteLine($"Deleted {configName}");
    return 0;
}

Java

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

private static void deleteUptimeCheckConfig(String checkName) throws IOException {
  try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
    client.deleteUptimeCheckConfig(checkName);
  } catch (Exception e) {
    usage("Exception deleting uptime check: " + e.toString());
    throw e;
  }
}

Go

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// delete is an example of deleting an uptime check. resourceName should be
// of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`.
func delete(w io.Writer, resourceName string) error {
	ctx := context.Background()
	client, err := monitoring.NewUptimeCheckClient(ctx)
	if err != nil {
		return fmt.Errorf("NewUptimeCheckClient: %w", err)
	}
	defer client.Close()
	req := &monitoringpb.DeleteUptimeCheckConfigRequest{
		Name: resourceName,
	}
	if err := client.DeleteUptimeCheckConfig(ctx, req); err != nil {
		return fmt.Errorf("DeleteUptimeCheckConfig: %w", err)
	}
	fmt.Fprintf(w, "Successfully deleted %q", resourceName)
	return nil
}

Node.js

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID';

const request = {
  // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check
  name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId),
};

console.log(`Deleting ${request.name}`);

// Delete an uptime check config
await client.deleteUptimeCheckConfig(request);
console.log(`${request.name} deleted.`);

PHP

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Monitoring\V3\Client\UptimeCheckServiceClient;
use Google\Cloud\Monitoring\V3\DeleteUptimeCheckConfigRequest;

/**
 * Example:
 * ```
 * delete_uptime_check($projectId, $configName);
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $configName
 */
function delete_uptime_check($projectId, $configName)
{
    $uptimeCheckClient = new UptimeCheckServiceClient([
        'projectId' => $projectId,
    ]);
    $deleteUptimeCheckConfigRequest = (new DeleteUptimeCheckConfigRequest())
        ->setName($configName);

    $uptimeCheckClient->deleteUptimeCheckConfig($deleteUptimeCheckConfigRequest);

    printf('Deleted an uptime check: ' . $configName . PHP_EOL);
}

Python

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

# `config_name` is the `name` field of an UptimeCheckConfig.
# See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.uptimeCheckConfigs#UptimeCheckConfig.
def delete_uptime_check_config(config_name: str) -> None:
    """Deletes the uptime check configuration

    Args:
        config_name: Uptime check configuration identity
    """
    client = monitoring_v3.UptimeCheckServiceClient()
    client.delete_uptime_check_config(request={"name": config_name})
    print("Deleted ", config_name)

Ruby

如要驗證 Monitoring,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

gem "google-cloud-monitoring"
require "google/cloud/monitoring"

def delete_uptime_check_config config_name
  client = Google::Cloud::Monitoring.uptime_check_service
  client.delete_uptime_check_config name: config_name
  puts "Deleted #{config_name}"
end

監控運作時間檢查

建議您建立快訊政策,以便在運作時間檢查失敗時收到通知。詳情請參閱「為運作時間檢查建立快訊政策」。

找出運作時間檢查的專屬 ID

建立運作時間檢查時,Monitoring 會指派一個 ID,稱為運作時間檢查 ID。此 ID 會嵌入到運作時間檢查的資源名稱內:

projects/PROJECT_ID/uptimeCheckConfigs/CHECK_ID

PROJECT_ID 是儲存正常運作時間檢查的專案 ID。如要進行 App Hub 設定,請選取 App Hub 主專案或啟用應用程式的資料夾管理專案。

建立或列出運作時間檢查的 Cloud Monitoring API 方法,都會在回應中納入運作時間檢查 ID。您也可以在Google Cloud 主控台的「運作時間詳細資料」頁面中,找到「設定」窗格內的運作時間檢查 ID。如要瞭解如何查看「運作時間詳細資料」頁面,請參閱本文的「查看運作時間檢查的詳細資料」一節。

後續步驟