Monitoring Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Monitoring API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

The samples on this page use custom, or user-defined, metrics to illustrate the use of the client libraries. The system-defined metrics described in the Metrics list are collected for you. You don't need to write any code to collect them, although the agent metrics do require the installation of the Cloud Monitoring agent. For more information on agent metrics, see the Agent metrics list.

For information about the previous Monitoring API client libraries, see Monitoring API Client Libraries.

Installing the client library


For more information, see Setting Up a C# Development Environment.

In Visual Studio 2013/2015, open the Package Manager Console and run this command:

Install-Package Google.Cloud.Monitoring.V3 -Pre


For more information, see Setting Up a Go Development Environment.

go get -u


For more information, see Setting Up a Java Development Environment.

如果您使用的是带有 BOM 的 Maven,请将以下代码添加到您的 pom.xml 文件中:



如果您使用的是不带 BOM 的 Maven,请将以下代码添加到您的依赖项中:


如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:

implementation platform('')

compile ''

如果您使用的是 sbt,请将以下代码添加到您的依赖项中:

libraryDependencies += "" % "google-cloud-monitoring" % "2.1.0"

如果您使用的是 IntelliJ 或 Eclipse,请通过以下 IDE 插件将客户端库添加到您的项目中:



For more information, see Setting Up a Node.js Development Environment.

npm install --save @google-cloud/monitoring


For more information, see Using PHP on Google Cloud.

composer require google/cloud-monitoring


For more information, see Setting Up a Python Development Environment.

pip install --upgrade google-cloud-monitoring


For more information, see Setting Up a Ruby Development Environment.

gem install google-cloud-monitoring

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For other ways to authenticate, see the GCP authentication documentation.

Cloud Console


  1. 在 Cloud Console 中,转到创建服务帐号页面。

  2. 选择一个项目。
  3. 服务帐号名称字段中,输入一个名称。 Cloud Console 会根据此名称填充服务帐号 ID 字段。

    服务帐号说明字段中,输入说明。例如,Service account for quickstart

  4. 点击创建
  5. 点击选择角色字段。


  6. 点击继续
  7. 点击完成以完成服务帐号的创建过程。



  1. 在 Cloud Console 中,点击您创建的服务帐号的电子邮件地址。
  2. 点击密钥
  3. 依次点击添加密钥创建新密钥
  4. 点击创建。JSON 密钥文件将下载到您的计算机上。
  5. 点击关闭


您可以使用本地机器上的 Cloud SDK 或在 Cloud Shell 中运行以下命令。

  1. 创建服务帐号。将 NAME 替换为服务帐号的名称。

    gcloud iam service-accounts create NAME
  2. 向服务帐号授予权限。将 PROJECT_ID 替换为您的项目 ID。

    gcloud projects add-iam-policy-binding PROJECT_ID --member="" --role="roles/owner"
  3. 生成密钥文件。将 FILE_NAME 替换为密钥文件的名称。

    gcloud iam service-accounts keys create FILE_NAME.json

通过设置环境变量 GOOGLE_APPLICATION_CREDENTIALS 向应用代码提供身份验证凭据。 将 [PATH] 替换为包含您的服务帐号密钥的 JSON 文件的路径。此变量仅适用于当前的 Shell 会话,因此,如果您打开新的会话,请重新设置该变量。

Linux 或 macOS



export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"


使用 PowerShell:






Using the client library

The following example shows how to use the client library.


See for instructions on using Visual Studio to build and run this sample C# code.

using System;
using System.Collections.Generic;
using Google.Cloud.Monitoring.V3;
using Google.Protobuf.WellKnownTypes;
using Google.Api;
using Google.Api.Gax.ResourceNames;

namespace GoogleCloudSamples
    public class QuickStart
        public static void Main(string[] args)
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            // Create client.
            MetricServiceClient metricServiceClient = MetricServiceClient.Create();

            // Initialize request argument(s).
            ProjectName name = new ProjectName(projectId);

            // Prepare a data point.
            TypedValue salesTotal = new TypedValue
                DoubleValue = 123.45
            Point dataPoint = new Point
                Value = salesTotal
            // Sets data point's interval end time to current time.
            DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            Timestamp timeStamp = new Timestamp
                Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds
            TimeInterval interval = new TimeInterval
                EndTime = timeStamp
            dataPoint.Interval = interval;

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

            // Prepare monitored resource.
            MonitoredResource resource = new MonitoredResource
                Type = "gce_instance"
            resource.Labels.Add("project_id", projectId);
            resource.Labels.Add("instance_id", "1234567890123456789");
            resource.Labels.Add("zone", "us-central1-f");

            // Create a new time series using inputs.
            TimeSeries timeSeriesData = new TimeSeries
                Metric = metric,
                Resource = resource

            // 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.");


// Sample monitoring-quickstart writes a data point to Stackdriver Monitoring.
package main

import (

	monitoring ""
	googlepb ""
	metricpb ""
	monitoredrespb ""
	monitoringpb ""

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := monitoring.NewMetricClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)

	// Sets your Google Cloud Platform project ID.
	projectID := "YOUR_PROJECT_ID"

	// Prepares an individual data point
	dataPoint := &monitoringpb.Point{
		Interval: &monitoringpb.TimeInterval{
			EndTime: &googlepb.Timestamp{
				Seconds: time.Now().Unix(),
		Value: &monitoringpb.TypedValue{
			Value: &monitoringpb.TypedValue_DoubleValue{
				DoubleValue: 123.45,

	// Writes time series data.
	if err := client.CreateTimeSeries(ctx, &monitoringpb.CreateTimeSeriesRequest{
		Name: monitoring.MetricProjectPath(projectID),
		TimeSeries: []*monitoringpb.TimeSeries{
				Metric: &metricpb.Metric{
					Type: "",
					Labels: map[string]string{
						"store_id": "Pittsburg",
				Resource: &monitoredrespb.MonitoredResource{
					Type: "global",
					Labels: map[string]string{
						"project_id": projectID,
				Points: []*monitoringpb.Point{
	}); err != nil {
		log.Fatalf("Failed to write time series data: %v", err)

	// Closes the client and flushes the data to Stackdriver.
	if err := client.Close(); err != nil {
		log.Fatalf("Failed to close client: %v", err)

	fmt.Printf("Done writing time series data.\n")


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Imports the Google Cloud client library

public class QuickstartSample {

  public static void main(String... args) throws Exception {
    // Your Google Cloud Platform project ID
    String projectId = System.getProperty("projectId");

    if (projectId == null) {
      System.err.println("Usage: QuickstartSample -DprojectId=YOUR_PROJECT_ID");

    // Instantiates a client
    MetricServiceClient metricServiceClient = MetricServiceClient.create();

    // Prepares an individual data point
    TimeInterval interval =
    TypedValue value = TypedValue.newBuilder().setDoubleValue(3.14).build();
    Point point = Point.newBuilder().setInterval(interval).setValue(value).build();

    List<Point> pointList = new ArrayList<>();

    ProjectName name = ProjectName.of(projectId);

    // Prepares the metric descriptor
    Map<String, String> metricLabels = new HashMap<String, String>();
    metricLabels.put("store_id", "Pittsburg");
    Metric metric =

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

    // Prepares the time series request
    TimeSeries timeSeries =
    List<TimeSeries> timeSeriesList = new ArrayList<>();

    CreateTimeSeriesRequest request =

    // Writes time series data

    System.out.printf("Done writing time series data.%n");



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

async function quickstart() {
  // Your Google Cloud Platform project ID
  const projectId =
    process.env.GCLOUD_PROJECT ||
    process.env.GOOGLE_CLOUD_PROJECT ||

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

  // Prepares an individual data point
  const dataPoint = {
    interval: {
      endTime: {
        seconds: / 1000,
    value: {
      // The amount of sales
      doubleValue: 123.45,

  // Prepares the time series request
  const request = {
    name: client.projectPath(projectId),
    timeSeries: [
        // Ties the data point to a custom metric
        metric: {
          type: '',
          labels: {
            store_id: 'Pittsburgh',
        resource: {
          type: 'global',
          labels: {
            project_id: projectId,
        points: [dataPoint],

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


# Includes the autoloader for libraries installed with composer
require_once __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Api\Metric;
use Google\Api\MonitoredResource;
use Google\Cloud\Monitoring\V3\MetricServiceClient;
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;

// These variables are set by the App Engine environment. To test locally,
// ensure these are set or manually change their values.
$projectId = getenv('GCLOUD_PROJECT') ?: 'YOUR_PROJECT_ID';
$instanceId = '1234567890123456789';
$zone = 'us-central1-f';

try {
    $client = new MetricServiceClient();
    $formattedProjectName = $client->projectName($projectId);
    $labels = [
        'instance_id' => $instanceId,
        'zone' => $zone,

    $m = new Metric();

    $r = new MonitoredResource();

    $value = new TypedValue();

    $timestamp = new Timestamp();

    $interval = new TimeInterval();

    $point = new Point();
    $points = [$point];

    $timeSeries = new TimeSeries();

    $client->createTimeSeries($formattedProjectName, [$timeSeries]);
    print('Successfully submitted a time series' . PHP_EOL);
} finally {


from import monitoring_v3

import time

client = monitoring_v3.MetricServiceClient()
# project = 'my-project'  # TODO: Update to your project ID.
project_name = f"projects/{project}"

series = monitoring_v3.TimeSeries()
series.metric.type = ""
series.resource.type = "gce_instance"
series.resource.labels["instance_id"] = "1234567890123456789"
series.resource.labels["zone"] = "us-central1-f"
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(request={"name": project_name, "time_series": [series]})
print("Successfully wrote time series.")


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

# Example metric label
# metric_label = "my-value"

# Instantiates a client
metric_service_client = Google::Cloud::Monitoring.metric_service
project_path = metric_service_client.project_path project: project_id

series =
series.metric = type:   "",
                                        labels: { "my_key" => metric_label }

resource = type: "gce_instance"
resource.labels["project_id"] = project_id
resource.labels["instance_id"] = "1234567890123456789"
resource.labels["zone"] = "us-central1-f"
series.resource = resource

point =
point.value = double_value: 3.14
now =
end_time = seconds: now.to_i, nanos: now.nsec
point.interval = end_time: end_time
series.points << point

metric_service_client.create_time_series name: project_path, time_series: [series]

puts "Successfully wrote time series."

Additional resources