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

יצירת מדדים בהגדרת המשתמש (שנקראים גם מדדים מותאמים אישית) באמצעות Cloud Monitoring API מאפשרת לתעד מדידות ספציפיות לאפליקציה, וליצור תרשימים או התראות לגביהן, בדיוק כמו מדדים מובְנים של Cloud Monitoring. בדומה למדדים מובְנים, כל מדד שמוגדר על ידי המשתמש משלב נקודות על הגרף, סוג מדד שמגדיר מה הנקודות מייצגות ומשאב במעקב שמזהה את מקור הנתונים.

כדי להוסיף לאפליקציה כלי למדידת ביצועים, מומלץ להשתמש בכלי קוד פתוח שלא תלוי בספק, כמו OpenTelemetry, במקום בממשקי API או בספריות לקוח שספציפיים לספק ולמוצר. למידע נוסף על מסגרות אלה, ראו יכולת תצפית למפתחי אפליקציות ובחירת גישה למדידת ביצועים.

אי אפשר להשתמש ב-Monitoring API כדי ליצור מדדים מבוססי-יומנים, שמפיקים נתוני מדדים מרשומות ביומן. במקום זאת, מערכת Cloud Logging יוצרת את מבני המדדים ושולחת את הנתונים ל-Cloud Monitoring בשבילכם. מידע נוסף זמין במאמרים יצירת מדדי מונה ויצירת מדדי התפלגות.

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

במאמר מדדים, סדרות זמנים ומשאבים מוסבר על המבנים שעליהם מבוססים כל המדדים.

כדי להשתמש ב-Cloud Monitoring, צריך פרויקט ב- Google Cloud עם חיוב מופעל. במקרה הצורך, מבצעים את הפעולות הבאות:

  1. בדף לבחירת הפרויקט במסוף Google Cloud , בוחרים פרויקט ב- Google Cloud או יוצרים אותו.

    התפקידים שנדרשים כדי לבחור או ליצור פרויקט

    • בחירת פרויקט: כדי לבחור פרויקט לא נדרש תפקיד IAM ספציפי – אתם יכולים לבחור כל פרויקט שקיבלתם בו תפקיד.
    • יצירת פרויקט: כדי ליצור פרויקט, צריך את התפקיד "יצירת פרויקטים" (roles/resourcemanager.projectCreator), שכולל את ההרשאה resourcemanager.projects.create. איך מקצים תפקידים?

    כניסה לדף לבחירת הפרויקט

  2. מוודאים שהחיוב מופעל בפרויקט ב- Google Cloud .

  3. מוודאים ש-Monitoring API מופעל. לפרטים, קראו את המאמר הפעלת Monitoring API.
  4. באפליקציות שפועלות מחוץ ל- Google Cloud, צריך לאמת את האפליקציה בפרויקט ב- Google Cloud באמצעות Application Default Credentials‏ (ADC) מקומיים. למידע נוסף אפשר לעיין במאמר הגדרת ADC לספק שירותי ענן מקומי או אחר.

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

כדי ליצור מדד בהגדרת המשתמש, אתם יכולים להגדיר אובייקט MetricDescriptor שמציין מידע שונה על המדד, או לכתוב נתוני מדדים. כשכותבים נתוני מדדים, המערכת של Monitoring יוצרת את תיאור המדד על סמך מבנה הנתונים שסיפקתם. למידע על תכנון תיאור מדד, קראו את המאמר תיאורי מדדים למדדים בהתאמה אישית.

יצירה אוטומטית של תיאורי מדדים

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

‫Cloud Monitoring יוצר MetricDescriptor חדש כשהאובייקט TimeSeries שנכלל בקריאה ל-timeSeries.create מפנה לאובייקט Metric שמציין שם של סוג מדד שלא קיים. ‫Cloud Monitoring משתמש בכללים הבאים כדי לאכלס את MetricDescriptor:

  • ‫type: הסוג מועתק מהשדה type של האובייקט Metric.
  • ‫name: השם נוצר ממזהה הפרויקט בהפעלת ה-method ומהערך של type באובייקט Metric.
  • ‫labels: התוויות שמופיעות באובייקט Metric. לכל תיאור תווית בתיאור המדד החדש יש את השדות הבאים:
    • ‫key: מפתח התווית באובייקט Metric.
    • valueType: STRING
    • ‫description: לא מוגדר
  • ‫metricKind: סוג המדד מוגדר כ-GAUGE, אלא אם מציינים את הפרמטר metricKind של האובייקט TimeSeries. כשמציינים את metricKind, המדד החדש הוא מהסוג הזה. אפשר לציין רק סוגים של GAUGE ו-CUMULATIVE.
  • ‫valueType: סוג הערך נלקח מהערך שהוקלד ב-Point שנכתב. סוג הערך חייב להיות BOOL,‏ INT64,‏ DOUBLE או DISTRIBUTION. כשמציינים סוג ערך בשדה valueType של TimeSeries, הסוג הזה צריך להתאים לסוג של Point.
  • ‫unit: לא מוגדר
  • description: "Auto created custom metric.".
  • ‫displayName: לא מוגדר

בקריאה אחת ל-timeSeries.create, אפשר לכלול כמה אובייקטים מסוג TimeSeries שמתייחסים לאותו סוג מדד שלא קיים. במקרה כזה, התוויות בתיאור המדד החדש מורכבות מאיחוד של כל התוויות באובייקטים מסוג Metric בכל הסדרות של נתונים כרונולוגיים בקריאה הזו ל-create.

השלב הבא: כתיבת מדדים בהגדרת משתמש.

יצירה ידנית של תיאורי מדדים

כדי ליצור תיאור מדד:

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

    1. בוחרים שם למדד המותאם אישית.

    2. בוחרים שם לתצוגה ותיאור למדד. השם המוצג מופיע במסוף Google Cloud .

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

    4. קובעים את סוג המדד, סוג הערך והיחידות (אופציונלי). לא כל סוגי הערכים וסוגי המדדים נתמכים במדדים שמוגדרים על ידי המשתמש. למידע נוסף על השדות האלה, קראו את המאמר סוגי ערכים וסוגי מדדים.

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

  2. קובעים את המשאבים במעקב שאליהם נכתבים נתוני המדדים. בוחרים מתוך הרשימה הבאה:

    • ‫aws_ec2_instance: מכונה של Amazon EC2.
    • ‫dataflow_job: משימת Dataflow.
    • gae_instance: מכונה של App Engine.
    • gce_instance: מכונה של Compute Engine.
    • ‫generic_node: צומת מחשוב שהמשתמש ציין.
    • ‫generic_task: משימה שהוגדרה על ידי המשתמש.
    • ‫gke_container: מכונה של קונטיינר GKE.
    • ‫global: משתמשים במשאב הזה כשאין סוג משאב אחר שמתאים. ברוב תרחישי השימוש, generic_node או generic_task הם אפשרויות טובות יותר מאשר global.
    • ‫k8s_cluster: אשכול Kubernetes.
    • ‫k8s_container: קונטיינר של Kubernetes.
    • ‫k8s_node: צומת Kubernetes.
    • ‫k8s_pod: פוד של Kubernetes.
  3. יוצרים אובייקט MetricDescriptor ומעבירים אותו כארגומנט לקריאה ל-method‏ metricDescriptors.create.

בדרך כלל, קריאה ל-metricDescriptors.create באמצעות שם סוג זהה לזה של תיאור מדד קיים היא שגיאה. עם זאת, אם כל השדות של האובייקט החדש מסוג MetricDescriptor תואמים בדיוק לשדות של התיאור הקיים, לא תהיה שגיאה אבל לא תהיה לכך השפעה.

בדוגמה הבאה יוצרים מדד מסוג gauge.

פרוטוקול

כדי ליצור תיאור מדד, משתמשים ב-method‏ metricDescriptors.create. אפשר להפעיל את ה-method הזו באמצעות הווידג'ט APIs Explorer בדף העזר של ה-method. מידע נוסף זמין ב-APIs Explorer.

אלה הפרמטרים לדוגמה של metricDescriptors.create:

  • שם (כתובת URL): projects/[PROJECT_ID]
  • גוף הבקשה: צריך לספק אובייקט MetricDescriptor, למשל:

    {
      "name": "",
      "description": "Daily sales records from all branch stores.",
      "displayName": "Sales",
      "type": "custom.googleapis.com/stores/sales",
      "metricKind": "GAUGE",
      "valueType": "DOUBLE",
      "unit": "{USD}",
      "labels": [
        {
          "key": "store_id",
          "valueType": "STRING",
          "description": "The ID of the store."
        },
      ],
    }
    

מזינים את הערכים האלה בשדות של הווידג'ט, ומשתמשים במזהה הפרויקט במקום [PROJECT_ID]:

תיבת הדו-שיח Try this API עם גוף הבקשה ליצירת תיאור מדד.

לוחצים על הכפתור Execute כדי להריץ את השיטה.

רוצה לנסות?

כשיוצרים מדד חדש, המערכת מתעלמת מהשדה name ב-MetricDescriptor ואפשר להשמיט אותו. השיטה create מחזירה את תיאור המדד החדש כשהשדה name מלא. בדוגמה הזו, זה מה שיוחזר:

"name": "projects/[PROJECT_ID]/metricDescriptors/custom.googleapis.com/stores/daily_sales"

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

C#

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

public static object CreateMetric(string projectId,
    string metricType = "custom.googleapis.com/stores/daily_sales")
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();

    // Prepare custom metric descriptor.      
    MetricDescriptor metricDescriptor = new MetricDescriptor();
    metricDescriptor.DisplayName = "Daily Sales";
    metricDescriptor.Description = "Daily sales records from all branch stores.";
    metricDescriptor.MetricKind = MetricKind.Gauge;
    metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
    metricDescriptor.Type = metricType;
    metricDescriptor.Unit = "{USD}";
    LabelDescriptor labels = new LabelDescriptor();
    labels.Key = "store_id";
    labels.ValueType = LabelDescriptor.Types.ValueType.String;
    labels.Description = "The ID of the store.";
    metricDescriptor.Labels.Add(labels);
    CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
    {
        ProjectName = new ProjectName(projectId),
    };
    request.MetricDescriptor = metricDescriptor;
    // Make the request.
    MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request);
    Console.WriteLine("Done creating metric descriptor:");
    Console.WriteLine(JObject.Parse($"{response}").ToString());
    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/genproto/googleapis/api/label"
	"google.golang.org/genproto/googleapis/api/metric"
	metricpb "google.golang.org/genproto/googleapis/api/metric"
)

// createCustomMetric creates a custom metric specified by the metric type.
func createCustomMetric(w io.Writer, projectID, metricType string) (*metricpb.MetricDescriptor, error) {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return nil, err
	}
	defer c.Close()
	md := &metric.MetricDescriptor{
		Name: "Custom Metric",
		Type: metricType,
		Labels: []*label.LabelDescriptor{{
			Key:         "environment",
			ValueType:   label.LabelDescriptor_STRING,
			Description: "An arbitrary measurement",
		}},
		MetricKind:  metric.MetricDescriptor_GAUGE,
		ValueType:   metric.MetricDescriptor_INT64,
		Unit:        "s",
		Description: "An arbitrary measurement",
		DisplayName: "Custom Metric",
	}
	req := &monitoringpb.CreateMetricDescriptorRequest{
		Name:             "projects/" + projectID,
		MetricDescriptor: md,
	}
	m, err := c.CreateMetricDescriptor(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("could not create custom metric: %w", err)
	}

	fmt.Fprintf(w, "Created %s\n", m.GetName())
	return m, nil
}

Java

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

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

try (final MetricServiceClient client = MetricServiceClient.create();) {
  ProjectName projectName = ProjectName.of(projectId);

  MetricDescriptor descriptor =
      MetricDescriptor.newBuilder()
          .setType(type)
          .addLabels(
              LabelDescriptor.newBuilder()
                  .setKey("store_id")
                  .setValueType(LabelDescriptor.ValueType.STRING))
          .setDescription("This is a simple example of a custom metric.")
          .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
          .setValueType(MetricDescriptor.ValueType.DOUBLE)
          .build();

  CreateMetricDescriptorRequest request =
      CreateMetricDescriptorRequest.newBuilder()
          .setName(projectName.toString())
          .setMetricDescriptor(descriptor)
          .build();

  descriptor = client.createMetricDescriptor(request);
  System.out.println("Created descriptor " + descriptor.getName());
}

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();

/**
 * TODO(developer): Uncomment and edit the following lines of code.
 */
// const projectId = 'YOUR_PROJECT_ID';
async function createMetricDescriptor() {
  const request = {
    name: client.projectPath(projectId),
    metricDescriptor: {
      description: 'Daily sales records from all branch stores.',
      displayName: 'Daily Sales',
      type: 'custom.googleapis.com/stores/daily_sales',
      metricKind: 'GAUGE',
      valueType: 'DOUBLE',
      unit: '{USD}',
      labels: [
        {
          key: 'store_id',
          valueType: 'STRING',
          description: 'The ID of the store.',
        },
      ],
    },
  };

  // Creates a custom metric descriptor
  const [descriptor] = await client.createMetricDescriptor(request);
  console.log('Created custom Metric:\n');
  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}`);
  });
}
createMetricDescriptor();

PHP

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

use Google\Api\LabelDescriptor;
use Google\Api\MetricDescriptor;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\CreateMetricDescriptorRequest;

/**
 * Create a new metric in Stackdriver Monitoring.
 * Example:
 * ```
 * create_metric($projectId);
 * ```
 *
 * @param string $projectId Your project ID
 */
function create_metric($projectId)
{
    $metrics = new MetricServiceClient([
        'projectId' => $projectId,
    ]);

    $projectName = 'projects/' . $projectId;

    $descriptor = new MetricDescriptor();
    $descriptor->setDescription('Daily sales records from all branch stores.');
    $descriptor->setDisplayName('Daily Sales');
    $descriptor->setType('custom.googleapis.com/stores/daily_sales');
    $descriptor->setMetricKind(MetricDescriptor\MetricKind::GAUGE);
    $descriptor->setValueType(MetricDescriptor\ValueType::DOUBLE);
    $descriptor->setUnit('{USD}');
    $label = new LabelDescriptor();
    $label->setKey('store_id');
    $label->setValueType(LabelDescriptor\ValueType::STRING);
    $label->setDescription('The ID of the store.');
    $labels = [$label];
    $descriptor->setLabels($labels);
    $createMetricDescriptorRequest = (new CreateMetricDescriptorRequest())
        ->setName($projectName)
        ->setMetricDescriptor($descriptor);

    $descriptor = $metrics->createMetricDescriptor($createMetricDescriptorRequest);
    printf('Created a metric: ' . $descriptor->getName() . PHP_EOL);
}

Python

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

from google.api import label_pb2 as ga_label
from google.api import metric_pb2 as ga_metric
from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"
descriptor = ga_metric.MetricDescriptor()
descriptor.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
descriptor.metric_kind = ga_metric.MetricDescriptor.MetricKind.GAUGE
descriptor.value_type = ga_metric.MetricDescriptor.ValueType.DOUBLE
descriptor.description = "This is a simple example of a custom metric."

labels = ga_label.LabelDescriptor()
labels.key = "TestLabel"
labels.value_type = ga_label.LabelDescriptor.ValueType.STRING
labels.description = "This is a test label"
descriptor.labels.append(labels)

descriptor = client.create_metric_descriptor(
    name=project_name, metric_descriptor=descriptor
)
print("Created {}.".format(descriptor.name))

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
project_name = client.project_path project: project_id

descriptor = Google::Api::MetricDescriptor.new(
  type:        metric_type,
  metric_kind: Google::Api::MetricDescriptor::MetricKind::GAUGE,
  value_type:  Google::Api::MetricDescriptor::ValueType::DOUBLE,
  description: "This is a simple example of a custom metric."
)

result = client.create_metric_descriptor name:              project_name,
                                         metric_descriptor: descriptor
p "Created #{result.name}"
p result

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

השלב הבא: כתיבת מדדים בהגדרת משתמש.

כתיבת מדדים בהתאמה אישית

אפשר לכתוב נתונים רק לסוגי מדדים שמוגדרים על ידי המשתמש. כדי לכתוב את הנתונים, משתמשים ב-method‏ timeSeries.create. אם הסדרה העיתית קיימת, השיטה הזו מוסיפה נקודת נתונים חדשה לסדרה העיתית הקיימת. אם סדרת הזמנים לא קיימת, השיטה יוצרת אותה ומוסיפה את הנתונים.

כדי לכתוב נקודות על הגרף, מעבירים רשימה של אובייקטים מסוג TimeSeries אל timeSeries.create. הרשימה יכולה להכיל עד 200 פריטים, וכל אובייקט ברשימה צריך לציין סדרת זמן שונה:

  • הערכים של השדות metric ו-resource מזהים אובייקט TimeSeries ספציפי. השדות האלה מייצגים את סוג המדד של הנתונים ואת המשאב במעקב שממנו נאספו הנתונים.
  • השמיטו את השדות metricKind ו-valueType, המערכת מתעלמת מהם כשכותבים נקודות על הגרף.
  • כל אובייקט TimeSeries יכול להכיל רק אובייקט Point אחד:

    • הערך ומרווח הזמן של הנקודה חייבים להיות עקביים עם ההגדרה של סוג המדד. למידע על מרווחי הזמן של סוגי המדדים השונים, ראו TimeInterval.
    • מרווח הזמן של הנקודה חייב להיות מאוחר יותר מכל נקודה שכבר קיימת בסדרת הזמן.
    • שעת הסיום של המרווח לא יכולה להיות יותר מ-25 שעות בעבר או יותר מ-5 דקות בעתיד.
  • כדי לכתוב יותר מנקודה אחת לאותה סדרת זמן, צריך להשתמש בקריאה נפרדת ל-method‏ timeSeries.create לכל נקודה. אל תכתבו נתונים לסדרת זמן אחת בקצב מהיר יותר מנקודה אחת כל 5 שניות. כשמוסיפים נקודות על הגרף לסדרות זמנים שונות, אין הגבלת קצב של יצירת בקשות.

פרוטוקול

כדי לכתוב נתוני מדדים, משתמשים ב-method‏ timeSeries.create. אפשר להפעיל את ה-method הזו באמצעות הווידג'ט APIs Explorer בדף העזר של ה-method. למידע נוסף, ראו APIs Explorer.

כדי לכתוב נקודה למדד stores/daily_sales שנוצר ביצירה ידנית של תיאורי מדדים:

  1. עוברים אל דף העזר של timeSeries.create.
  2. מזינים את הפרמטרים הבאים בווידג'ט של APIs Explorer.
  3. לוחצים על הכפתור Execute.

משתמשים בפרמטרים לדוגמה הבאים:

  • name: projects/[PROJECT_ID]
  • גוף הבקשה: כולל רשימה של אובייקטים מסוג TimeSeries. בדוגמה הבאה יש רק סדרת זמנים אחת ברשימה.

    {
     "timeSeries": [
      {
       "metric": {
        "type": "custom.googleapis.com/my_metric",
        "labels": {
         "my_label": "my_value"
        }
       },
       "resource": {
        "type": "gce_instance",
        "labels": {
         "project_id": "[PROJECT_ID]",
         "instance_id": "1234567890123456789",
         "zone": "us-central1-f"
        }
       },
       "points": [
        {
         "interval": {
          "endTime": "2018-06-01T10:00:00-04:00"
         },
         "value": {
          "doubleValue": 123.45
         }
        }
       ]
      }
     ]
    }
    

רוצה לנסות?

C#

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

public static object WriteTimeSeriesData(string projectId)
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    ProjectName name = new ProjectName(projectId);
    // Prepare a data point. 
    Point dataPoint = new Point();
    TypedValue salesTotal = new TypedValue();
    salesTotal.DoubleValue = 123.45;
    dataPoint.Value = salesTotal;
    Timestamp timeStamp = new Timestamp();
    timeStamp.Seconds = (long)(DateTime.UtcNow - s_unixEpoch).TotalSeconds;
    TimeInterval interval = new TimeInterval();
    interval.EndTime = timeStamp;
    dataPoint.Interval = interval;

    // Prepare custom metric.
    Metric metric = new Metric();
    metric.Type = "custom.googleapis.com/stores/daily_sales";
    metric.Labels.Add("store_id", "Pittsburgh");

    // Prepare monitored resource.
    MonitoredResource resource = new MonitoredResource();
    resource.Type = "global";
    resource.Labels.Add("project_id", projectId);

    // Create a new time series using inputs.
    TimeSeries timeSeriesData = new TimeSeries();
    timeSeriesData.Metric = metric;
    timeSeriesData.Resource = resource;
    timeSeriesData.Points.Add(dataPoint);

    // Add newly created time series to list of time series to be written.
    IEnumerable<TimeSeries> timeSeries = new List<TimeSeries> { timeSeriesData };
    // Write time series data.
    metricServiceClient.CreateTimeSeries(name, timeSeries);
    Console.WriteLine("Done writing time series data:");
    Console.WriteLine(JObject.Parse($"{timeSeriesData}").ToString());
    return 0;
}

Go

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


// writeTimeSeriesValue writes a value for the custom metric created
func writeTimeSeriesValue(projectID, metricType string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	now := &timestamp.Timestamp{
		Seconds: time.Now().Unix(),
	}
	req := &monitoringpb.CreateTimeSeriesRequest{
		Name: "projects/" + projectID,
		TimeSeries: []*monitoringpb.TimeSeries{{
			Metric: &metricpb.Metric{
				Type: metricType,
				Labels: map[string]string{
					"environment": "STAGING",
				},
			},
			Resource: &monitoredres.MonitoredResource{
				Type: "gce_instance",
				Labels: map[string]string{
					"instance_id": "test-instance",
					"zone":        "us-central1-f",
				},
			},
			Points: []*monitoringpb.Point{{
				Interval: &monitoringpb.TimeInterval{
					StartTime: now,
					EndTime:   now,
				},
				Value: &monitoringpb.TypedValue{
					Value: &monitoringpb.TypedValue_Int64Value{
						Int64Value: rand.Int63n(10),
					},
				},
			}},
		}},
	}
	log.Printf("writeTimeseriesRequest: %+v\n", req)

	err = c.CreateTimeSeries(ctx, req)
	if err != nil {
		return fmt.Errorf("could not write time series value, %w ", err)
	}
	return nil
}

Java

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

String projectId = System.getProperty("projectId");

// Prepares an individual data point
TimeInterval interval =
    TimeInterval.newBuilder()
        .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
        .build();
TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build();
Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

List<Point> pointList = new ArrayList<>();
pointList.add(point);

ProjectName name = ProjectName.of(projectId);

// Prepares the metric descriptor
Map<String, String> metricLabels = new HashMap<>();
Metric metric =
    Metric.newBuilder()
        .setType("custom.googleapis.com/my_metric")
        .putAllLabels(metricLabels)
        .build();

// Prepares the monitored resource descriptor
Map<String, String> resourceLabels = new HashMap<>();
resourceLabels.put("instance_id", "1234567890123456789");
resourceLabels.put("zone", "us-central1-f");

MonitoredResource resource =
    MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();

// Prepares the time series request
TimeSeries timeSeries =
    TimeSeries.newBuilder()
        .setMetric(metric)
        .setResource(resource)
        .addAllPoints(pointList)
        .build();

List<TimeSeries> timeSeriesList = new ArrayList<>();
timeSeriesList.add(timeSeries);

CreateTimeSeriesRequest request =
    CreateTimeSeriesRequest.newBuilder()
        .setName(name.toString())
        .addAllTimeSeries(timeSeriesList)
        .build();

// Writes time series data
try (final MetricServiceClient client = MetricServiceClient.create();) {
  client.createTimeSeries(request);
}
System.out.println("Done writing time series value.");

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 writeTimeSeriesData() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';

  const dataPoint = {
    interval: {
      endTime: {
        seconds: Date.now() / 1000,
      },
    },
    value: {
      doubleValue: 123.45,
    },
  };

  const timeSeriesData = {
    metric: {
      type: 'custom.googleapis.com/stores/daily_sales',
      labels: {
        store_id: 'Pittsburgh',
      },
    },
    resource: {
      type: 'global',
      labels: {
        project_id: projectId,
      },
    },
    points: [dataPoint],
  };

  const request = {
    name: client.projectPath(projectId),
    timeSeries: [timeSeriesData],
  };

  // Writes time series data
  const result = await client.createTimeSeries(request);
  console.log('Done writing time series data.', result);
}
writeTimeSeriesData();

PHP

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

use Google\Api\Metric;
use Google\Api\MonitoredResource;
use Google\Cloud\Monitoring\V3\Client\MetricServiceClient;
use Google\Cloud\Monitoring\V3\CreateTimeSeriesRequest;
use Google\Cloud\Monitoring\V3\Point;
use Google\Cloud\Monitoring\V3\TimeInterval;
use Google\Cloud\Monitoring\V3\TimeSeries;
use Google\Cloud\Monitoring\V3\TypedValue;
use Google\Protobuf\Timestamp;

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

    $projectName = 'projects/' . $projectId;

    $endTime = new Timestamp();
    $endTime->setSeconds(time());
    $interval = new TimeInterval();
    $interval->setEndTime($endTime);

    $value = new TypedValue();
    $value->setDoubleValue(123.45);

    $point = new Point();
    $point->setValue($value);
    $point->setInterval($interval);
    $points = [$point];

    $metric = new Metric();
    $metric->setType('custom.googleapis.com/stores/daily_sales');
    $labels = ['store_id' => 'Pittsburg'];
    $metric->setLabels($labels);

    $resource = new MonitoredResource();
    $resource->setType('global');
    $labels = ['project_id' => $projectId];
    $resource->setLabels($labels);

    $timeSeries = new TimeSeries();
    $timeSeries->setMetric($metric);
    $timeSeries->setResource($resource);
    $timeSeries->setPoints($points);
    $createTimeSeriesRequest = (new CreateTimeSeriesRequest())
        ->setName($projectName)
        ->setTimeSeries([$timeSeries]);

    $metrics->createTimeSeries($createTimeSeriesRequest);

    printf('Done writing time series data.' . PHP_EOL);
}

Python

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

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
project_name = f"projects/{project_id}"

series = monitoring_v3.TimeSeries()
series.metric.type = "custom.googleapis.com/my_metric" + str(uuid.uuid4())
series.resource.type = "gce_instance"
series.resource.labels["instance_id"] = "1234567890123456789"
series.resource.labels["zone"] = "us-central1-c"
series.metric.labels["TestLabel"] = "My Label Data"
now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
interval = monitoring_v3.TimeInterval(
    {"end_time": {"seconds": seconds, "nanos": nanos}}
)
point = monitoring_v3.Point({"interval": interval, "value": {"double_value": 3.14}})
series.points = [point]
client.create_time_series(name=project_name, time_series=[series])

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
project_name = client.project_path project: project_id

series = Google::Cloud::Monitoring::V3::TimeSeries.new
series.metric = Google::Api::Metric.new type: metric_type

resource = Google::Api::MonitoredResource.new type: "global"
resource.labels["project_id"] = project_id
series.resource = resource

point = Google::Cloud::Monitoring::V3::Point.new
point.value = Google::Cloud::Monitoring::V3::TypedValue.new double_value: 3.14
now = Time.now
end_time = Google::Protobuf::Timestamp.new seconds: now.to_i, nanos: now.nsec
point.interval = Google::Cloud::Monitoring::V3::TimeInterval.new end_time: end_time
series.points << point

client.create_time_series name: project_name, time_series: [series]
p "Time series created."

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

מחיקת מדדים שהוגדרו על ידי המשתמש

כדי למחוק מדד בהגדרת המשתמש, צריך למחוק את תיאור המדד שלו. אי אפשר למחוק את נתוני הסדרות העיתיות שמאוחסנים בפרויקט ב- Google Cloud , אבל אם מוחקים את תיאור המדד, אי אפשר לגשת לנתונים. הנתונים נמחקים בהתאם למדיניות שמירת הנתונים.

אי אפשר למחוק את תיאור המדד של מדד מובנה.

כדי למחוק את תיאור המדד, מפעילים את ה-method‏ metricDescriptors.delete.

פרוטוקול

כדי למחוק תיאור מדד, משתמשים ב-method‏ metricDescriptors.delete. אפשר להפעיל את ה-method הזו באמצעות הווידג'ט APIs Explorer בדף העזר של ה-method. למידע נוסף, ראו APIs Explorer.

כדי למחוק את המדד stores/daily_sales שנוצר ביצירה ידנית של תיאורי מדדים:

  1. עוברים אל דף העזר של metricDescriptors.delete.
  2. מזינים את השם של תיאור המדד בווידג'ט של APIs Explorer:

    name: projects/[PROJECT_ID]/metricDescriptors/custom.googleapis.com/stores/daily_sales

  3. לוחצים על הכפתור Execute.

רוצה לנסות?

C#

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

public static object DeleteMetric(string projectId, string metricType)
{
    // Create client.
    MetricServiceClient metricServiceClient = MetricServiceClient.Create();
    // Initialize request argument(s).
    MetricDescriptorName name = new MetricDescriptorName(projectId, metricType);
    // Make the request.
    metricServiceClient.DeleteMetricDescriptor(name);
    Console.WriteLine($"Done deleting metric descriptor: {name}");
    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"
)

// deleteMetric deletes the given metric. name should be of the form
// "projects/PROJECT_ID/metricDescriptors/METRIC_TYPE".
func deleteMetric(w io.Writer, name string) error {
	ctx := context.Background()
	c, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		return err
	}
	defer c.Close()
	req := &monitoringpb.DeleteMetricDescriptorRequest{
		Name: name,
	}

	if err := c.DeleteMetricDescriptor(ctx, req); err != nil {
		return fmt.Errorf("could not delete metric: %w", err)
	}
	fmt.Fprintf(w, "Deleted metric: %q\n", name)
	return nil
}

Java

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

final String projectId = System.getProperty("projectId");
try (final MetricServiceClient client = MetricServiceClient.create();) {
  MetricDescriptorName metricName = MetricDescriptorName.of(projectId, type);
  client.deleteMetricDescriptor(metricName);
  System.out.println("Deleted descriptor " + type);
}

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 deleteMetricDescriptor() {
  /**
   * TODO(developer): Uncomment and edit the following lines of code.
   */
  // const projectId = 'YOUR_PROJECT_ID';
  // const metricId = 'custom.googleapis.com/stores/daily_sales';

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

  // Deletes a metric descriptor
  const [result] = await client.deleteMetricDescriptor(request);
  console.log(`Deleted ${metricId}`, result);
}
deleteMetricDescriptor();

PHP

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

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

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

    $metricPath = $metrics->metricDescriptorName($projectId, $metricId);
    $deleteMetricDescriptorRequest = (new DeleteMetricDescriptorRequest())
        ->setName($metricPath);
    $metrics->deleteMetricDescriptor($deleteMetricDescriptorRequest);

    printf('Deleted a metric: ' . $metricPath . PHP_EOL);
}

Python

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

from google.cloud import monitoring_v3

client = monitoring_v3.MetricServiceClient()
client.delete_metric_descriptor(name=descriptor_name)
print("Deleted metric descriptor {}.".format(descriptor_name))

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

client.delete_metric_descriptor name: metric_name
p "Deleted metric descriptor #{metric_name}."

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

שינוי מדד בהתאמה אישית

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

כדי להוסיף תוויות למדד קיים שמוגדר על ידי המשתמש, משתמשים ב-method‏ timeSeries.create וכוללים את התוויות החדשות בנתוני הסדרה העיתית. התוויות מתווספות לתיאור המדד אם התוויות שאתם מנסים לכתוב תקינות, ומספר התוויות הכולל קטן מ-30.

לאחר מכן, נתוני סדרת הזמנים נכתבים כאילו התווית הייתה שם מההתחלה.

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

אי אפשר לשנות את השם של מדד.

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