取得工作指標

示範如何取得描述工作進度的一組指標。

程式碼範例

C#

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

using Google.Cloud.Dataflow.V1Beta3;
using Google.Protobuf.WellKnownTypes;

public sealed partial class GeneratedMetricsV1Beta3ClientSnippets
{
    /// <summary>Snippet for GetJobMetrics</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void GetJobMetricsRequestObject()
    {
        // Create client
        MetricsV1Beta3Client metricsV1Beta3Client = MetricsV1Beta3Client.Create();
        // Initialize request argument(s)
        GetJobMetricsRequest request = new GetJobMetricsRequest
        {
            ProjectId = "",
            JobId = "",
            StartTime = new Timestamp(),
            Location = "",
        };
        // Make the request
        JobMetrics response = metricsV1Beta3Client.GetJobMetrics(request);
    }
}

Go

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


import (
	"context"
	"fmt"
	"io"

	dataflow "cloud.google.com/go/dataflow/apiv1beta3"
	dataflowpb "cloud.google.com/go/dataflow/apiv1beta3/dataflowpb"
)

// getJobMetrics retrieves runtime metrics for a specific Dataflow job.
func getJobMetrics(ctx context.Context, w io.Writer, projectID string, locationID string, jobID string) error {
	client, err := dataflow.NewMetricsV1Beta3Client(ctx)
	if err != nil {
		return fmt.Errorf("NewMetricsV1Beta3Client failed: %w", err)
	}
	defer client.Close()

	req := &dataflowpb.GetJobMetricsRequest{
		ProjectId: projectID,
		Location:  locationID,
		JobId:     jobID,
	}

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

	fmt.Fprintf(w, "Retrieved %d metrics for job %s\n", len(resp.GetMetrics()), jobID)
	for _, metric := range resp.GetMetrics() {
		fmt.Fprintf(w, "Metric: %s\n", metric.GetName().GetName())
	}

	return nil
}

Java

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

import com.google.dataflow.v1beta3.GetJobMetricsRequest;
import com.google.dataflow.v1beta3.JobMetrics;
import com.google.dataflow.v1beta3.MetricUpdate;
import com.google.dataflow.v1beta3.MetricsV1Beta3Client;
import java.io.IOException;

public class GetJobMetrics {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "us-central1";
    String jobId = "example-job-id";
    getJobMetrics(projectId, locationId, jobId);
  }

  public static void getJobMetrics(String projectId, String locationId, String jobId)
      throws IOException {
    try (MetricsV1Beta3Client client = MetricsV1Beta3Client.create()) {
      GetJobMetricsRequest request =
          GetJobMetricsRequest.newBuilder()
              .setProjectId(projectId)
              .setLocation(locationId)
              .setJobId(jobId)
              .build();

      JobMetrics response = client.getJobMetrics(request);
      System.out.printf("Retrieved %d metrics for job %s.%n", response.getMetricsCount(), jobId);
      for (MetricUpdate metric : response.getMetricsList()) {
        System.out.printf("Metric name: %s%n", metric.getName().getName());
      }
    }
  }
}

Node.js

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

'use strict';

const {MetricsV1Beta3Client} = require('@google-cloud/dataflow');
const {status} = require('@grpc/grpc-js');

const client = new MetricsV1Beta3Client();

/**
 * Retrieves metrics for a specific Cloud Dataflow job.
 *
 * @param {string} projectId - The Google Cloud project ID containing the Dataflow job.
 * @param {string} locationId - The regional endpoint where the Dataflow job runs (for example, 'us-central1').
 * @param {string} jobId - The server-generated ID of the Dataflow job.
 */
async function getJobMetrics(projectId, locationId, jobId) {
  try {
    const request = {
      projectId,
      location: locationId,
      jobId,
    };

    const [response] = await client.getJobMetrics(request);

    console.log(`Retrieved metrics for job: ${jobId}`);
    if (response.metrics) {
      for (const metric of response.metrics) {
        const metricName = metric.name ? metric.name.name : 'Unnamed metric';
        console.log(`Metric: ${metricName}`);
      }
    }
    return response;
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Job ${jobId} not found in project ${projectId} and location ${locationId}.`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied accessing metrics for job ${jobId}.`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid arguments provided for job ${jobId}: ${err.message}`);
    } else {
      console.error(`Failed to retrieve job metrics: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { getJobMetrics };

Python

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

import google.api_core.exceptions
from google.cloud import dataflow_v1beta3

client = dataflow_v1beta3.MetricsV1Beta3Client()


def get_job_metrics(project_id: str, location_id: str, job_id: str) -> None:
    """Retrieves metric information for a specified Cloud Dataflow job.

    Args:
        project_id: The Google Cloud project ID hosting the Dataflow job.
        location_id: The Dataflow regional endpoint location (for example, 'us-central1').
        job_id: The server-generated Dataflow job ID.
    """
    request = dataflow_v1beta3.GetJobMetricsRequest(
        project_id=project_id,
        location=location_id,
        job_id=job_id,
    )

    try:
        response = client.get_job_metrics(request=request)
        print(f"Retrieved metrics for job: {job_id}")
        print(f"Metrics count: {len(response.metrics)}")
        for metric in response.metrics:
            metric_name = metric.name.name if metric.name else "Unnamed metric"
            print(f" - Metric name: {metric_name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Request failed: {e}")

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱Google Cloud 範例瀏覽工具。