管理運作時間檢查

如要在端點變更或資源淘汰時,確保可用性監控與服務保持一致,您可以列出、查看、編輯及刪除運作時間檢查。您可以使用Google Cloud 控制台、Google Cloud CLI、Cloud Monitoring API 或用戶端程式庫,執行這些管理工作。

事前準備

在儲存運作時間檢查的 Google Cloud 專案中,完成下列操作。如要設定 App Hub,請選取 App Hub 主專案或管理專案。

  • 請根據您打算如何使用本頁範例,選取對應的分頁標籤:

    控制台

    使用 Google Cloud 控制台存取 Google Cloud 服務和 API 時,不需要設定驗證機制。

    gcloud

    在 Google Cloud 控制台啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

    C#

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    Go

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    Java

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    Node.js

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    PHP

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    Python

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    小茹

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

    1. 安裝 Google Cloud CLI。

    2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    3. 如果您使用的是本機殼層,請為使用者帳戶建立本機驗證憑證:

      gcloud auth application-default login

      如果您使用的是 Cloud Shell,則不必執行這項操作。

      如果系統傳回驗證錯誤,且您使用的是外部識別資訊提供者 (IdP),請確認您已使用聯合身分登入 gcloud CLI。

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

    REST

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

      安裝 Google Cloud CLI。

      若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI。

    詳情請參閱 Google Cloud 驗證說明文件中的「使用 REST 進行驗證」一節。

列出所有運作時間檢查

控制台

  1. 在 Google Cloud 控制台中,前往「 Uptime checks」(運作時間檢查) 頁面:

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

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

    以下是「運作時間檢查」頁面的範例:

    運作時間檢查示例總覽 (含篩選器)。

  2. 在 Google Cloud 控制台的工具列中,選取 Google Cloud 專案。如要設定 App Hub,請選取 App Hub 主專案或管理專案。

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

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

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

    如果有多個篩選器,除非插入 OR 篩選器,否則系統會自動以邏輯 AND 連結篩選器。上例使用 OR 篩選器,因此如果運作時間檢查的名稱與 default 或 Testing 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」(運作時間檢查) 頁面:

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

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

  2. 在 Google Cloud 控制台的工具列中,選取 Google Cloud 專案。如要設定 App Hub,請選取 App Hub 主專案或管理專案。
  3. 找出要查看的運作時間檢查,然後按一下其名稱。

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

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

    「Uptime details」(運作時間詳細資料) 頁面包含下列資訊:

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

      舉例來說,在 25 分鐘內,從所有區域執行的運作時間檢查 (週期為一分鐘) 會從 6 個位置各收到 25 個要求,總共 150 個要求。如果資訊主頁回報的正常運作時間為 83.3%,則 150 個要求中有 125 個成功。

    • 「Passed checks」(通過的檢查) 和「Uptime check latency」(運作時間檢查延遲時間) 窗格會以圖表顯示通過的檢查數量,以及各項檢查的延遲時間 (以時間為函數)。

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

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

    • 「Alert Policies」(警告政策) 窗格會列出相關聯警告政策的資訊。範例資訊主頁中已設定一項警告政策。

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

編輯運作時間檢查

您可以修改運作時間檢查的部分欄位。例如,您可能希望更頻繁地執行檢查,或增加與回應驗證相關的逾時時間。不過,如果運作時間檢查未設定正確的通訊協定、資源類型或資源,請刪除目前的運作時間檢查,並建立新的檢查。

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

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

控制台

  1. 在 Google Cloud 控制台中,前往「 Uptime checks」(運作時間檢查) 頁面:

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

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

  2. 在 Google Cloud 控制台的工具列中,選取 Google Cloud 專案。如要設定 App Hub,請選取 App Hub 主專案或管理專案。
  3. 找出要編輯的運作時間檢查,然後執行下列任一操作:

    • 按一下「更多」圖示 ,然後選取「編輯」。
    • 查看運作時間檢查詳細資料,然後按一下「Edit」(編輯)。
  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」(運作時間檢查) 頁面:

    前往「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 控制台的「Uptime details」(運作時間詳細資料) 頁面的「Configuration」(設定) 窗格中,找到運作時間檢查 ID。如要瞭解如何查看「Uptime details」(運作時間詳細資料) 頁面,請參閱本文的「查看運作時間檢查詳細資料」一節。

後續步驟