Google Cloud Monitoring

2.30.0 · active · verified Sat Mar 28

The `google-cloud-monitoring` Python client library provides programmatic access to Google Cloud Monitoring, allowing users to collect metrics, events, and metadata from Google Cloud, AWS, and other sources. It enables the creation of custom metrics, reading of time series data, and integration with Google Cloud Observability for dashboards, charts, and alerts. The library is part of the larger `google-cloud-python` ecosystem and is actively maintained, with frequent updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Google Cloud Monitoring client, optionally create a custom metric descriptor (checking if it exists first), and then write a single data point for that custom metric as a time series. Remember to replace `your-project-id` with your actual Google Cloud project ID and ensure proper authentication is set up. The `GOOGLE_CLOUD_PROJECT` environment variable is the recommended way to provide the project ID.

import os
from google.cloud import monitoring_v3
from google.protobuf import timestamp_pb2

# Set your Google Cloud Project ID using environment variable or replace 'your-project-id'
project_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')

if project_id == 'your-project-id':
    print("WARNING: Please set the GOOGLE_CLOUD_PROJECT environment variable or replace 'your-project-id' with your actual project ID.")

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

# Define a custom metric descriptor if it doesn't exist
metric_type = 'custom.googleapis.com/my_app/request_count'
metric_descriptor_name = f"{project_name}/metricDescriptors/{metric_type}"

try:
    client.get_metric_descriptor(name=metric_descriptor_name)
    print(f"Metric descriptor '{metric_type}' already exists.")
except Exception:
    print(f"Creating metric descriptor '{metric_type}'...")
    descriptor = monitoring_v3.MetricDescriptor()
    descriptor.type = metric_type
    descriptor.metric_kind = monitoring_v3.MetricDescriptor.MetricKind.GAUGE
    descriptor.value_type = monitoring_v3.MetricDescriptor.ValueType.DOUBLE
    descriptor.description = "Count of requests to my application."
    client.create_metric_descriptor(name=project_name, metric_descriptor=descriptor)
    print("Metric descriptor created.")

# Create a time series
series = monitoring_v3.TimeSeries()
series.metric.type = metric_type

# Assign to a monitored resource (e.g., 'global' for metrics not tied to a specific resource)
series.resource.type = 'global'
# For other resource types (e.g., 'gce_instance', 'cloud_run_revision'), add relevant labels:
# series.resource.labels['instance_id'] = '1234567890'
# series.resource.labels['zone'] = 'us-central1-a'

now = timestamp_pb2.Timestamp()
now.FromDatetime(timestamp_pb2.datetime_helper.utcnow())

point = monitoring_v3.Point()
point.interval.end_time = now
point.value.double_value = 42.0 # Your metric value

series.points.append(point)

# Write the time series data
try:
    client.create_time_series(name=project_name, time_series=[series])
    print(f"Successfully wrote a custom metric '{metric_type}' to Cloud Monitoring for project '{project_id}'.")
    print("You can view this metric in the Google Cloud Console under Monitoring -> Metrics Explorer.")
except Exception as e:
    print(f"Error writing time series: {e}")

view raw JSON →