Monitoring Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Stackdriver 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 Stackdriver agents. 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


go get -u


For more information, see Setting Up a Java Development Environment. Maven을 사용한다면 pom.xml 파일에 다음을 추가하세요.
Gradle을 사용한다면 종속 항목에 다음을 추가하세요.
compile ''
SBT를 사용한다면 종속 항목에 다음을 추가하세요.
libraryDependencies += "" % "google-cloud-monitoring" % "1.75.0"

IntelliJ 또는 Eclipse를 사용하는 경우 다음과 같은 IDE 플러그인을 사용하여 클라이언트 라이브러리를 프로젝트에 추가할 수 있습니다.

이 플러그인은 서비스 계정의 키 관리와 같은 추가 기능을 제공합니다. 자세한 내용은 각 플러그인의 문서를 참조하세요.


For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/monitoring


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 more information, see the GCP authentication documentation .

GCP Console

  1. GCP Console에서 서비스 계정 키 만들기 페이지로 이동합니다.

    서비스 계정 키 만들기 페이지로 이동
  2. 서비스 계정 목록에서 새 서비스 계정을 선택합니다.
  3. 서비스 계정 이름 필드에 이름을 입력합니다.
  4. 역할 목록에서 프로젝트 > 소유자를 선택합니다.

    참고: 역할 필드가 리소스에 액세스할 수 있도록 서비스 계정을 승인합니다. 나중에 GCP Console을 사용하여 이 필드를 보고 변경할 수 있습니다. 프로덕션 애플리케이션을 개발하는 경우 프로젝트 > 소유자보다 세부적인 권한을 지정합니다. 자세한 내용은 서비스 계정에 역할 부여를 참조하세요.
  5. 만들기를 클릭합니다. 키가 포함된 JSON 파일이 컴퓨터에 다운로드됩니다.


로컬 머신 또는 Cloud Shell에서 Cloud SDK를 사용하여 다음 명령어를 실행할 수 있습니다.

  1. 서비스 계정을 만듭니다. [NAME]을 서비스 계정 이름으로 바꿉니다.

    gcloud iam service-accounts create [NAME]
  2. 서비스 계정에 권한을 부여합니다. [PROJECT_ID]를 프로젝트 ID로 바꿉니다.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID]" --role "roles/owner"
    참고: 역할 필드가 리소스에 액세스할 수 있도록 서비스 계정을 승인합니다. 이 필드는 나중에 GCP Console을 사용하여 보고 변경할 수 있습니다. 프로덕션 애플리케이션을 개발하는 경우 프로젝트 > 소유자보다 세부적인 권한을 지정합니다. 자세한 내용은 서비스 계정에 역할 부여를 참조하세요.
  3. 키 파일을 생성합니다. [FILE_NAME]을 키 파일 이름으로 바꿉니다.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID]

환경 변수 GOOGLE_APPLICATION_CREDENTIALS를 설정하여 애플리케이션 코드에 사용자 인증 정보를 제공합니다. [PATH]를 서비스 계정 키가 포함된 JSON 파일의 파일 경로로 바꾸고 [FILE_NAME]을 파일 이름으로 바꿉니다. 이 변수는 현재 셸 세션에만 적용되므로 새 세션을 연 경우 변수를 다시 설정합니다.

Linux 또는 macOS



export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"






명령 프롬프트:


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;

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

            // Prepare custom metric.
            Metric metric = new Metric();
            metric.Type = "";
            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;

            // 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 = TimeInterval.newBuilder()
    TypedValue value = TypedValue.newBuilder()
    Point point = Point.newBuilder()

    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 = Metric.newBuilder()

    // Prepares the monitored resource descriptor
    Map<String, String> resourceLabels = new HashMap<String, String>();
    resourceLabels.put("project_id", projectId);
    MonitoredResource resource = MonitoredResource.newBuilder()

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

    CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()

    // 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 || 'YOUR_PROJECT_ID';

  // 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 = client.project_path(project)

series = monitoring_v3.types.TimeSeries()
series.metric.type = ''
series.resource.type = 'gce_instance'
series.resource.labels['instance_id'] = '1234567890123456789'
series.resource.labels['zone'] = 'us-central1-f'
point = series.points.add()
point.value.double_value = 3.14
now = time.time()
point.interval.end_time.seconds = int(now)
point.interval.end_time.nanos = int(
    (now - point.interval.end_time.seconds) * 10**9)
client.create_time_series(project_name, [series])
print('Successfully wrote time series.')


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

# Instantiates a client
metric_service_client =
project_path = Google::Cloud::Monitoring::V3::MetricServiceClient.project_path project_id

series =
series.metric = type: ""

resource = type: "gce_instance"
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.usec
point.interval = end_time: end_time
series.points << point

metric_service_client.create_time_series project_path, [series]

puts "Successfully wrote time series."

Additional resources

이 페이지가 도움이 되었나요? 평가를 부탁드립니다.

다음에 대한 의견 보내기...

Stackdriver Monitoring
도움이 필요하시나요? 지원 페이지를 방문하세요.