הצגת רשימה של סוגי מדדים ומשאבים

במאמר הזה מוסבר איך להשתמש ב-Cloud Monitoring API כדי לקבל רשימות או תיאורים של:

  • סוגי מדדים שהוגדרו על ידי המשתמש בפרויקט.
  • סוגי מדדים של צד שלישי עם נתונים של סדרות עיתיות בפרויקט. מדדים שנוצרו על ידי Bindplane הם דוגמאות למדדים של צד שלישי. למדדים של Bindplane יש תחילית של workload.googleapis.com/3rd-party-app-name/. רשימה מלאה של מדדים נתמכים של אפליקציות צד שלישי זמינה במסמכי התיעוד של Bindplane.
  • סוגי מדדים מובנים שסופקו על ידי Google Cloud. סוגי המדדים האלה יכולים לעזור לכם לתכנן את המדדים המוגדרים על ידי המשתמש. מידע על המדדים האלה זמין גם בתיעוד. אפשר לעיין ברשימת המדדים.
  • סוגי המשאבים במעקב שזמינים לפרויקט. מידע על המשאבים האלה מופיע גם במאמרי העזרה. אפשר לעיין ברשימת המשאבים במעקב.
יש כמה דרכים להשתמש בשיטות ה-API שמתוארות במסמך הזה:

  • כדי להריץ את השיטות בלי לכתוב קוד, הדוגמאות בכרטיסיות Protocol בדף הזה משתמשות ב-API Explorer מבוסס-טפסים. (מידע נוסף על הכלי הזה זמין במאמר APIs Explorer).

  • כדי ללמוד איך להשתמש בשיטות משפות תכנות נבחרות, אפשר לעיין בדוגמאות הקוד שניתנות להרצה בדף הזה.

לפני שמתחילים

רשימת תיאורי מדדים

מתארי מדדים הם הסכימות שמגדירות מדדים. כדי למצוא פרטים על המדדים שמעניינים אתכם, אפשר לעיין בתיאורי המדדים הזמינים:

  • מדדים מובנים: אתם יכולים להגיש בקשות API לכל פרויקט קיים, או להשתמש במסמכי התיעוד של רשימות המדדים.
  • מדדים חיצוניים ומדדים שהוגדרו על ידי המשתמש: צריך לשלוח את בקשת ה-API לפרויקט שבו מוגדר המדד שהוגדר על ידי המשתמש או שבו קיימים נתונים של סדרות זמן לגבי המדד.

מידע נוסף על שמות של סוגי מדדים זמין במאמר מוסכמות למתן שמות.

הצגת רשימה של סוגי מדדים

כדי לקבל רשימה עדכנית של מתארי מדדים, משתמשים בשיטה metricDescriptors.list. כדי לצמצם את קבוצת סוגי המדדים שמוחזרים, משתמשים במסנן. במאמר סוגי ערכים וסוגי מדדים יש מידע שיעזור לכם להחליט אילו סוגי מדדים לחפש.

פרוטוקול

  1. פותחים את דף העזר של metricDescriptors.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: projects/PROJECT_ID. מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud .
    • filter (מסנן): metric.type = starts_with("compute.googleapis.com")
  3. לוחצים על Execute.

בדוגמה הבאה של תגובה מוצגים חלק מתיאורי המדדים שאוחזרו:

    "metricDescriptors": [
      {
        "name": "projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_bytes_count",
        "labels": [{...}],
         ...
         "description": "Count of incoming bytes dropped by the firewall.",
         "displayName": "Dropped bytes",
         "type": "compute.googleapis.com/firewall/dropped_bytes_count",
         ...
      },
      {
         "name": "projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count",
         "labels": [{...}],
         ...
         "description": "Count of incoming packets dropped by the firewall.",
         "displayName": "Dropped packets",
         "type": "compute.googleapis.com/firewall/dropped_packets_count",
      },
      ...
    ]

הערך type בכל תיאור מזהה את תיאור המדד, לדוגמה, compute.googleapis.com/firewall/dropped_packets_count. הערך הזה נקרא לפעמים גם 'סוג המדד' או 'שם סוג המדד'.

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object ListMetrics(string projectId)
{
    MetricServiceClient client = MetricServiceClient.Create();
    ProjectName projectName = new ProjectName(projectId);
    PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName);
    foreach (MetricDescriptor metric in metrics)
    {
        Console.WriteLine($"{metric.Name}: {metric.DisplayName}");
    }
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"google.golang.org/api/iterator"
)

// listMetrics lists all the metrics available to be monitored in the API.
func listMetrics(w io.Writer, projectID string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()

	req := &monitoringpb.ListMetricDescriptorsRequest{
		Name: "projects/" + projectID,
	}
	iter := c.ListMetricDescriptors(ctx, req)

	for {
		resp, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Could not list metrics: %w", err)
		}
		fmt.Fprintf(w, "%v\n", resp.GetType())
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Your Google Cloud Platform project ID
String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

ListMetricDescriptorsRequest request =
    ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build();

// Instantiates a client
try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request);

  System.out.println("Listing descriptors: ");

  for (MetricDescriptor d : response.iterateAll()) {
    System.out.println(d.getName() + " " + d.getDisplayName());
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

  // Lists metric descriptors
  const [descriptors] = await client.listMetricDescriptors(request);
  console.log('Metric Descriptors:');
  descriptors.forEach(descriptor => console.log(descriptor.name));
}
listMetricDescriptors();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListMetricDescriptorsRequest;

/**
 * Example:
 * ```
 * list_descriptors($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function list_descriptors($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;
    $listMetricDescriptorsRequest = (new ListMetricDescriptorsRequest())
        ->setName($projectName);
    $descriptors = $metrics->listMetricDescriptors($listMetricDescriptorsRequest);

    printf('Metric Descriptors:' . PHP_EOL);
    foreach ($descriptors->iterateAllElements() as $descriptor) {
        printf($descriptor->getName() . PHP_EOL);
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
descriptors = client.list_metric_descriptors(name=project_name)
for descriptor in descriptors:
    print(descriptor.type)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

results = client.list_metric_descriptors name: project_name
results.each do |descriptor|
  p descriptor.type
end

אם נתקלתם בבעיה, תוכלו לעיין במאמר פתרון בעיות בקריאות ל-API.

קבלת תיאורי מדדים

כדי לקבל מידע על סוג מדד יחיד, משתמשים בשיטת metricDescriptors.get. השיטה הזו מחזירה תיאור מדד.

כדי לאחזר מתאר מדד ספציפי, צריך לספק ל-API את השם המלא של המדד. השם המלא מורכב משני רכיבים:

  • קידומת שכוללת projects/PROJECT_ID/metricDescriptors.
  • הערך type שמזהה את תיאור המדד, לדוגמה, compute.googleapis.com/firewall/dropped_packets_count. מידע נוסף על הערך type זמין בכרטיסייה Protocol במאמר List metric types.

דוגמה לשם המלא של מדד:

projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count

פרוטוקול

כדי לקבל את המתאר של מדד /firewall/dropped_packets_countCompute Engine, מבצעים את הפעולות הבאות:

  1. פותחים את דף העזר של metricDescriptors.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count

      מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud .

  3. לוחצים על Execute.

בדוגמה הבאה לתגובה מוצג תיאור המדד:

    {
        "name": "projects/PROJECT_ID/metricDescriptors/compute.googleapis.com/firewall/dropped_packets_count",
        "labels": [
          {
            "key": "instance_name",
            "description": "The name of the VM instance."
          }
        ],
        "metricKind": "DELTA",
        "valueType": "INT64",
        "unit": "1",
        "description": "Count of incoming packets dropped by the firewall.",
        "displayName": "Dropped packets",
        "type": "compute.googleapis.com/firewall/dropped_packets_count",
      }

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object GetMetricDetails(string projectId, string metricType)
{
    MetricServiceClient client = MetricServiceClient.Create();
    MetricDescriptorName name = new MetricDescriptorName(projectId, metricType);
    try
    {
        var response = client.GetMetricDescriptor(name);
        string metric = JObject.Parse($"{response}").ToString();
        Console.WriteLine($"{ metric }");
    }
    catch (Grpc.Core.RpcException ex)
        when (ex.Status.StatusCode == Grpc.Core.StatusCode.NotFound)
    { }
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

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

// getMetricDescriptor gets the descriptor for the given metricType and prints
// information about it. metricType is the type of the metric, for example
// compute.googleapis.com/firewall/dropped_packets_count.
func getMetricDescriptor(w io.Writer, projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer c.Close()
	req := &monitoringpb.GetMetricDescriptorRequest{
		Name: fmt.Sprintf("projects/%s/metricDescriptors/%s", projectID, metricType),
	}
	resp, err := c.GetMetricDescriptor(ctx, req)
	if err != nil {
		return fmt.Errorf("could not get custom metric: %w", err)
	}

	fmt.Fprintf(w, "Name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Description: %v\n", resp.GetDescription())
	fmt.Fprintf(w, "Type: %v\n", resp.GetType())
	fmt.Fprintf(w, "Metric Kind: %v\n", resp.GetMetricKind())
	fmt.Fprintf(w, "Value Type: %v\n", resp.GetValueType())
	fmt.Fprintf(w, "Unit: %v\n", resp.GetUnit())
	fmt.Fprintf(w, "Labels:\n")
	for _, l := range resp.GetLabels() {
		fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
	}
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Your Google Cloud Platform project ID
final String projectId = System.getProperty("projectId");

MetricDescriptorName descriptorName = MetricDescriptorName.of(projectId, type);

try (final MetricServiceClient client = MetricServiceClient.create();) {
  MetricDescriptor response = client.getMetricDescriptor(descriptorName);

  System.out.println("Printing metrics descriptor: " + response);
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

async function getMetricDescriptor() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const metricId = 'custom.googleapis.com/your/id';

  const request = {
    name: client.projectMetricDescriptorPath(projectId, metricId),
  };

  // Retrieves a metric descriptor
  const [descriptor] = await client.getMetricDescriptor(request);
  console.log(`Name: ${descriptor.displayName}`);
  console.log(`Description: ${descriptor.description}`);
  console.log(`Type: ${descriptor.type}`);
  console.log(`Kind: ${descriptor.metricKind}`);
  console.log(`Value Type: ${descriptor.valueType}`);
  console.log(`Unit: ${descriptor.unit}`);
  console.log('Labels:');
  descriptor.labels.forEach(label => {
    console.log(`  ${label.key} (${label.valueType}) - ${label.description}`);
  });
}
getMetricDescriptor();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\GetMetricDescriptorRequest;

/**
 * Example:
 * ```
 * get_descriptor($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $metricId  The ID of the Metric Descriptor to get
 */
function get_descriptor($projectId, $metricId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $metricName = $metrics->metricDescriptorName($projectId, $metricId);
    $getMetricDescriptorRequest = (new GetMetricDescriptorRequest())
        ->setName($metricName);
    $descriptor = $metrics->getMetricDescriptor($getMetricDescriptorRequest);

    printf('Name: ' . $descriptor->getDisplayName() . PHP_EOL);
    printf('Description: ' . $descriptor->getDescription() . PHP_EOL);
    printf('Type: ' . $descriptor->getType() . PHP_EOL);
    printf('Metric Kind: ' . $descriptor->getMetricKind() . PHP_EOL);
    printf('Value Type: ' . $descriptor->getValueType() . PHP_EOL);
    printf('Unit: ' . $descriptor->getUnit() . PHP_EOL);
    printf('Labels:' . PHP_EOL);
    foreach ($descriptor->getLabels() as $labels) {
        printf('  %s (%s) - %s' . PHP_EOL,
            $labels->getKey(),
            $labels->getValueType(),
            $labels->getDescription());
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
descriptor = client.get_metric_descriptor(name=metric_name)
pprint.pprint(descriptor)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

# Example metric type
# metric_type = "custom.googleapis.com/my_metric"

client = Google::Cloud::Monitoring.metric_service
metric_name = client.metric_descriptor_path project:           project_id,
                                            metric_descriptor: metric_type

descriptor = client.get_metric_descriptor name: metric_name
p descriptor

אם נתקלתם בבעיה, תוכלו לעיין במאמר פתרון בעיות בקריאות ל-API.

רשימת משאבים במעקב

משאבים במעקב הם ישויות בענן שאפשר לעקוב אחריהן. כדי לראות את סוגי הישויות שיש להן מדדים, אפשר לעיין ברשימה של סוגי המשאבים במעקב.

כדי לקבל מידע על משאבים במעקב, אפשר לשלוח בקשות API לכל פרויקט קיים, או להשתמש במסמכי העזרה של רשימת המשאבים במעקב.

רשימת סוגי המשאבים

כדי לקבל רשימה עדכנית של סוגי המשאבים במעקב מ-Monitoring API, משתמשים ב-method‏ monitoredResourceDescriptors.list ומזינים את מזהה הפרויקט.

פרוטוקול

  1. פותחים את דף העזר monitoredResourceDescriptors.list.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: projects/PROJECT_ID. מחליפים את PROJECT_ID במזהה של הפרויקט ב- Google Cloud .
  3. לוחצים על Execute.

בדוגמה הבאה של תגובה מוצגים חלק מסוגי המשאבים המפוקחים שמוחזרים:

    {
    "resourceDescriptors": [
    {
      "type": "aiplatform.googleapis.com/Endpoint",
      "displayName": "AI Platform Endpoint",
      "description": "A Cloud AI Platform API Endpoint where Models are deployed into it.",
      "labels": [{...}],
      "name": "projects/PROJECT_ID/monitoredResourceDescriptors/aiplatform.googleapis.com/Endpoint",
    },
    {
      "type": "aiplatform.googleapis.com/Featurestore",
      "displayName": "AI Platform Feature Store",
      "description": "A Cloud AI Platform Feature Store.",
      "labels": [{...}],
      "name": "projects/PROJECT_ID/monitoredResourceDescriptors/aiplatform.googleapis.com/Featurestore",
    },

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

        public static object ListMonitoredResources(string projectId)
        {
            Console.WriteLine("Starting to List Monitored Resources...");
            MetricServiceClient client = MetricServiceClient.Create();
            ProjectName projectName = new ProjectName(projectId);

            PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor>
                resources = client.ListMonitoredResourceDescriptors(projectName);
            if (resources.Any())
            {
                foreach (MonitoredResourceDescriptor resource in resources.Take(10))
                {
                    Console.WriteLine($"{resource.Name}: {resource.DisplayName}");
                }
            }
            else
            { 
                Console.WriteLine("No resources found.");
            }
            return 0;
        }

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	monitoring "cloud.google.com/go/monitoring/apiv3"
	"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
	"google.golang.org/api/iterator"
)

// listMonitoredResources lists all the resources available to be monitored.
func listMonitoredResources(w io.Writer, projectID string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()

	req := &monitoringpb.ListMonitoredResourceDescriptorsRequest{
		Name: "projects/" + projectID,
	}
	iter := c.ListMonitoredResourceDescriptors(ctx, req)

	for {
		resp, err := iter.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Could not list time series: %w", err)
		}
		fmt.Fprintf(w, "%v\n", resp)
	}
	fmt.Fprintln(w, "Done")
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Your Google Cloud Platform project ID
String projectId = System.getProperty("projectId");
ProjectName name = ProjectName.of(projectId);

ListMonitoredResourceDescriptorsRequest request =
    ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name.toString()).build();

System.out.println("Listing monitored resource descriptors: ");

// Instantiates a client
try (final MetricServiceClient client = MetricServiceClient.create();) {
  ListMonitoredResourceDescriptorsPagedResponse response =
      client.listMonitoredResourceDescriptors(request);

  for (MonitoredResourceDescriptor d : response.iterateAll()) {
    System.out.println(d.getType());
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

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

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

  // Lists monitored resource descriptors
  const [descriptors] =
    await client.listMonitoredResourceDescriptors(request);
  console.log('Monitored Resource Descriptors:');
  descriptors.forEach(descriptor => {
    console.log(descriptor.name);
    console.log(`  Type: ${descriptor.type}`);
    if (descriptor.labels) {
      console.log('  Labels:');
      descriptor.labels.forEach(label => {
        console.log(
          `    ${label.key} (${label.valueType}): ${label.description}`
        );
      });
    }
    console.log();
  });
}
listMonitoredResourceDescriptors();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\ListMonitoredResourceDescriptorsRequest;

/**
 * Example:
 * ```
 * list_resources('your-project-id');
 * ```
 *
 * @param string $projectId Your project ID
 */
function list_resources($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);
    $projectName = 'projects/' . $projectId;
    $listMonitoredResourceDescriptorsRequest = (new ListMonitoredResourceDescriptorsRequest())
        ->setName($projectName);
    $descriptors = $metrics->listMonitoredResourceDescriptors($listMonitoredResourceDescriptorsRequest);
    foreach ($descriptors->iterateAllElements() as $descriptor) {
        print($descriptor->getType() . PHP_EOL);
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
resource_descriptors = client.list_monitored_resource_descriptors(name=project_name)
for descriptor in resource_descriptors:
    print(descriptor.type)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

client = Google::Cloud::Monitoring.metric_service
project_name = client.project_path project: project_id

results = client.list_monitored_resource_descriptors name: project_name
results.each do |descriptor|
  p descriptor.type
end

אם נתקלתם בבעיה, תוכלו לעיין במאמר פתרון בעיות בקריאות ל-API.

קבלת תיאורי משאבים

כדי לקבל מתאר ספציפי של משאב מנוטר, משתמשים בשיטה monitoredResourceDescriptors.get.

כדי לאחזר מתאר ספציפי של משאב במעקב, צריך לספק ל-API את השם המלא של המתאר. השם המלא מורכב משני רכיבים:

  • קידומת שכוללת projects/PROJECT_ID/monitoredResourceDescriptors.
  • הערך type שמזהה את מתאר המשאב המנוטר, לדוגמה, gce_instance. מידע נוסף על הערך type מופיע בכרטיסייה פרוטוקול במאמר רשימת סוגי משאבים.

דוגמה לשם המלא של משאב במעקב:

projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance

פרוטוקול

כדי לקבל את המתאר של סוג המשאב gce_instance, מבצעים את הפעולות הבאות:

  1. פותחים את דף העזר monitoredResourceDescriptors.get.

  2. בחלונית עם התווית Try this method (אפשר לנסות את השיטה הזו), מזינים את הפרטים הבאים:

    • name: projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance

      מחליפים את PROJECT_ID במזהה הפרויקט ב- Google Cloud .

  3. לוחצים על Execute.

בדוגמה הבאה של תגובה מוצג התיאור של המשאב המפוקח הזה:

    {
      "type": "gce_instance",
      "displayName": "VM Instance",
      "description": "A virtual machine instance hosted in Compute Engine.",
      "labels": [
        {
          "key": "project_id",
          "description": "The identifier of the Google Cloud project associated with this resource, such as \"my-project\"."
        },
        {
          "key": "instance_id",
          "description": "The numeric VM instance identifier assigned by Compute Engine."
        },
        {
          "key": "zone",
          "description": "The Compute Engine zone in which the VM is running."
        }
      ],
      "name": "projects/PROJECT_ID/monitoredResourceDescriptors/gce_instance"
    }

כדי לראות את הבקשה כפקודת curl, כבקשת HTTP או ב-JavaScript, לוחצים על מסך מלא ב-APIs Explorer.

C#

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

public static object GetMonitoredResource(string projectId, string resourceId)
{
    MetricServiceClient client = MetricServiceClient.Create();
    MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName(projectId, resourceId);
    var response = client.GetMonitoredResourceDescriptor(name);
    string resource = JObject.Parse($"{response}").ToString();
    Console.WriteLine($"{ resource }");
    return 0;
}

Go

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

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

// getMonitoredResource gets the descriptor for the given resourceType and
// prints information about it. resource should be of the form
// "projects/[PROJECT_ID]/monitoredResourceDescriptors/[RESOURCE_TYPE]".
func getMonitoredResource(w io.Writer, resource string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricClient: %w", err)
	}
	defer c.Close()
	req := &monitoringpb.GetMonitoredResourceDescriptorRequest{
		Name: resource,
	}
	resp, err := c.GetMonitoredResourceDescriptor(ctx, req)
	if err != nil {
		return fmt.Errorf("could not get custom metric: %w", err)
	}

	fmt.Fprintf(w, "Name: %v\n", resp.GetName())
	fmt.Fprintf(w, "Description: %v\n", resp.GetDescription())
	fmt.Fprintf(w, "Type: %v\n", resp.GetType())
	fmt.Fprintf(w, "Labels:\n")
	for _, l := range resp.GetLabels() {
		fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription())
	}
	return nil
}

Java

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

void getMonitoredResource(String resourceId) throws IOException {
  String projectId = System.getProperty("projectId");

  try (final MetricServiceClient client = MetricServiceClient.create();) {
    MonitoredResourceDescriptorName name =
        MonitoredResourceDescriptorName.of(projectId, resourceId);
    MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name);
    System.out.println("Retrieved Monitored Resource: " + gson.toJson(response));
  }
}

Node.js

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

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

async function getMonitoredResourceDescriptor() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const resourceType = 'some_resource_type, e.g. cloudsql_database';

  const request = {
    name: client.projectMonitoredResourceDescriptorPath(
      projectId,
      resourceType
    ),
  };

  // Lists monitored resource descriptors
  const [descriptor] = await client.getMonitoredResourceDescriptor(request);

  console.log(`Name: ${descriptor.displayName}`);
  console.log(`Description: ${descriptor.description}`);
  console.log(`Type: ${descriptor.type}`);
  console.log('Labels:');
  descriptor.labels.forEach(label => {
    console.log(`  ${label.key} (${label.valueType}) - ${label.description}`);
  });
}
getMonitoredResourceDescriptor();

PHP

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\GetMonitoredResourceDescriptorRequest;

/**
 * Example:
 * ```
 * get_resource('your-project-id', 'gcs_bucket');
 * ```
 *
 * @param string $projectId Your project ID
 * @param string $resourceType The resource type of the monitored resource.
 */
function get_resource($projectId, $resourceType)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $metricName = $metrics->monitoredResourceDescriptorName($projectId, $resourceType);
    $getMonitoredResourceDescriptorRequest = (new GetMonitoredResourceDescriptorRequest())
        ->setName($metricName);
    $resource = $metrics->getMonitoredResourceDescriptor($getMonitoredResourceDescriptorRequest);

    printf('Name: %s' . PHP_EOL, $resource->getName());
    printf('Type: %s' . PHP_EOL, $resource->getType());
    printf('Display Name: %s' . PHP_EOL, $resource->getDisplayName());
    printf('Description: %s' . PHP_EOL, $resource->getDescription());
    printf('Labels:' . PHP_EOL);
    foreach ($resource->getLabels() as $labels) {
        printf('  %s (%s) - %s' . PHP_EOL,
            $labels->getKey(),
            $labels->getValueType(),
            $labels->getDescription());
    }
}

Python

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
resource_path = (
    f"projects/{project_id}/monitoredResourceDescriptors/{resource_type_name}"
)
descriptor = client.get_monitored_resource_descriptor(name=resource_path)
pprint.pprint(descriptor)

Ruby

כדי לבצע אימות ב-Monitoring, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

# Your Google Cloud Platform project ID
# project_id = "YOUR_PROJECT_ID"

# The resource type
# resource_type = "gce_instance"

client = Google::Cloud::Monitoring.metric_service
resource_path = client.monitored_resource_descriptor_path(
  project:                       project_id,
  monitored_resource_descriptor: resource_type
)

result = client.get_monitored_resource_descriptor name: resource_path
p result

אם נתקלתם בבעיה, תוכלו לעיין במאמר פתרון בעיות בקריאות ל-API.

המאמרים הבאים