Stackdriver Monitoring-Clientbibliotheken

Auf dieser Seite werden die ersten Schritte mit den neuen Cloud-Clientbibliotheken für die Stackdriver Monitoring API erläutert. Weitere Informationen zu den Clientbibliotheken für die Cloud-APIs einschließlich der älteren Google APIs-Clientbibliotheken finden Sie unter Erläuterung der Clientbibliotheken.

Informationen zu den früheren Clientbibliotheken für die Stackdriver Monitoring API finden Sie unter Clientbibliotheken für die Stackdriver Monitoring API.

Die Clientbibliothek installieren

C#

Öffnen Sie in Visual Studio 2013/2015 die Package Manager Console und führen Sie folgenden Befehl aus:
Install-Package Google.Cloud.Monitoring.V3 -Pre

Go

go get cloud.google.com/go/monitoring/apiv3

Java

Wenn Sie Maven verwenden, fügen Sie der Datei pom.xml Folgendes hinzu:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-monitoring</artifactId>
    <version></version>
</dependency>

Wenn Sie Gradle verwenden, fügen Sie den Abhängigkeiten Folgendes hinzu:

compile group: 'com.google.cloud', name: 'google-cloud-monitoring', version: ''

Node.js

npm install --save @google-cloud/monitoring

Python

pip install --upgrade google-cloud-monitoring

Ruby

gem install google-cloud-monitoring

Clientbibliothek verwenden

Im Folgenden finden Sie ein Beispiel zur Verwendung der Clientbibliothek. Für die Ausführung auf Ihrer lokalen Workstation müssen Sie zunächst das Google Cloud SDK installieren und mithilfe des folgenden Befehls eine Authentifizierung durchführen:

gcloud auth application-default login

Weitere Informationen zur Authentifizierung in anderen Umgebungen finden Sie im Autorisierungsleitfaden für Google Cloud Platform.

C#

Wie Sie diesen C#-Beispielcode mit Visual Studio erstellen und ausführen, lesen Sie in der Datei README.md.
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 = "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.");
        }
    }
}
Weitere Informationen zur Clientbibliothek für die Stackdriver Monitoring API finden Sie in der C# API-Referenzdokumentation.

Go

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

import (
	"fmt"
	"log"
	"time"

	// Imports the Stackdriver Monitoring client package.
	monitoring "cloud.google.com/go/monitoring/apiv3"
	googlepb "github.com/golang/protobuf/ptypes/timestamp"
	"golang.org/x/net/context"
	metricpb "google.golang.org/genproto/googleapis/api/metric"
	monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
)

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: "custom.googleapis.com/stores/daily_sales",
					Labels: map[string]string{
						"store_id": "Pittsburg",
					},
				},
				Resource: &monitoredrespb.MonitoredResource{
					Type: "global",
					Labels: map[string]string{
						"project_id": projectID,
					},
				},
				Points: []*monitoringpb.Point{
					dataPoint,
				},
			},
		},
	}); err != nil {
		log.Fatalf("Failed to write time series data: %v", err)
	}

	fmt.Printf("Done writing time series data.\n")
}
Weitere Informationen zur Clientbibliothek für die Stackdriver Monitoring API finden Sie in der Go API-Referenzdokumentation.

Java

import com.google.api.Metric;
import com.google.api.MonitoredResource;

// Imports the Google Cloud client library
import com.google.cloud.monitoring.spi.v3.MetricServiceClient;

import com.google.monitoring.v3.CreateTimeSeriesRequest;
import com.google.monitoring.v3.Point;
import com.google.monitoring.v3.ProjectName;
import com.google.monitoring.v3.TimeInterval;
import com.google.monitoring.v3.TimeSeries;
import com.google.monitoring.v3.TypedValue;
import com.google.protobuf.util.Timestamps;

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

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");
      return;
    }

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

    // 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.create(projectId);

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

    // Prepares the monitored resource descriptor
    Map<String, String> resourceLabels = new HashMap<String, String>();
    resourceLabels.put("project_id", projectId);
    MonitoredResource resource = MonitoredResource.newBuilder()
        .setType("global")
        .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()
        .setNameWithProjectName(name)
        .addAllTimeSeries(timeSeriesList)
        .build();

    // Writes time series data
    metricServiceClient.createTimeSeries(request);

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

    metricServiceClient.close();
  }
}
Weitere Informationen zur Clientbibliothek für die Stackdriver Monitoring API finden Sie in der Java API-Referenzdokumentation.

Node.js

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

// Your Google Cloud Platform project ID
const projectId = 'YOUR_PROJECT_ID';

// Instantiates a client
const client = Monitoring.v3().metricServiceClient();

// Prepares an individual data point
const dataPoint = {
  interval: {
    endTime: {
      seconds: Date.now() / 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: 'custom.googleapis.com/stores/daily_sales',
        labels: {
          store_id: 'Pittsburgh'
        }
      },
      resource: {
        type: 'global',
        labels: {
          project_id: projectId
        }
      },
      points: [
        dataPoint
      ]
    }
  ]
};

// Writes time series data
client.createTimeSeries(request)
  .then((results) => {
    console.log(`Done writing time series data.`);
  });
Weitere Informationen zur Clientbibliothek für die Stackdriver Monitoring API finden Sie in der Node.js API-Referenzdokumentation.

Python

from google.cloud import monitoring

client = monitoring.Client()

resource = client.resource(
    type_='gce_instance',
    labels={
        'instance_id': '1234567890123456789',
        'zone': 'us-central1-f',
    }
)

metric = client.metric(
    type_='custom.googleapis.com/my_metric',
    labels={}
)

# Default arguments use endtime datetime.utcnow()
client.write_point(metric, resource, 3.14)
print('Successfully wrote time series.')
Weitere Informationen zur Clientbibliothek für die Stackdriver Monitoring API finden Sie in der Python API-Referenzdokumentation.

Zusätzliche Ressourcen