{"id":498,"library":"google-cloud-monitoring","title":"Google Cloud Monitoring","description":"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.","status":"active","version":"2.30.0","language":"python","source_language":"en","source_url":"https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-monitoring","tags":["google cloud","monitoring","metrics","observability","gcp"],"install":[{"cmd":"pip install google-cloud-monitoring","lang":"bash","label":"Install latest version"}],"dependencies":[],"imports":[{"note":"The `monitoring_v3` module provides the client for the current v3 API. Direct import of `monitoring` often refers to an older client library pattern (pre-2.0.0) which may lack features or have different interfaces.","wrong":"from google.cloud import monitoring","symbol":"MetricServiceClient","correct":"from google.cloud import monitoring_v3"},{"note":"Used for managing service-level monitoring configurations.","symbol":"ServiceMonitoringServiceClient","correct":"from google.cloud import monitoring_v3"},{"note":"Required for creating and writing time series data points to Cloud Monitoring.","symbol":"TimeSeries","correct":"from google.cloud.monitoring_v3 import TimeSeries"}],"quickstart":{"code":"import os\nfrom google.cloud import monitoring_v3\nfrom google.protobuf import timestamp_pb2\n\n# Set your Google Cloud Project ID using environment variable or replace 'your-project-id'\nproject_id = os.environ.get('GOOGLE_CLOUD_PROJECT', 'your-project-id')\n\nif project_id == 'your-project-id':\n    print(\"WARNING: Please set the GOOGLE_CLOUD_PROJECT environment variable or replace 'your-project-id' with your actual project ID.\")\n\nclient = monitoring_v3.MetricServiceClient()\nproject_name = f\"projects/{project_id}\"\n\n# Define a custom metric descriptor if it doesn't exist\nmetric_type = 'custom.googleapis.com/my_app/request_count'\nmetric_descriptor_name = f\"{project_name}/metricDescriptors/{metric_type}\"\n\ntry:\n    client.get_metric_descriptor(name=metric_descriptor_name)\n    print(f\"Metric descriptor '{metric_type}' already exists.\")\nexcept Exception:\n    print(f\"Creating metric descriptor '{metric_type}'...\")\n    descriptor = monitoring_v3.MetricDescriptor()\n    descriptor.type = metric_type\n    descriptor.metric_kind = monitoring_v3.MetricDescriptor.MetricKind.GAUGE\n    descriptor.value_type = monitoring_v3.MetricDescriptor.ValueType.DOUBLE\n    descriptor.description = \"Count of requests to my application.\"\n    client.create_metric_descriptor(name=project_name, metric_descriptor=descriptor)\n    print(\"Metric descriptor created.\")\n\n# Create a time series\nseries = monitoring_v3.TimeSeries()\nseries.metric.type = metric_type\n\n# Assign to a monitored resource (e.g., 'global' for metrics not tied to a specific resource)\nseries.resource.type = 'global'\n# For other resource types (e.g., 'gce_instance', 'cloud_run_revision'), add relevant labels:\n# series.resource.labels['instance_id'] = '1234567890'\n# series.resource.labels['zone'] = 'us-central1-a'\n\nnow = timestamp_pb2.Timestamp()\nnow.FromDatetime(timestamp_pb2.datetime_helper.utcnow())\n\npoint = monitoring_v3.Point()\npoint.interval.end_time = now\npoint.value.double_value = 42.0 # Your metric value\n\nseries.points.append(point)\n\n# Write the time series data\ntry:\n    client.create_time_series(name=project_name, time_series=[series])\n    print(f\"Successfully wrote a custom metric '{metric_type}' to Cloud Monitoring for project '{project_id}'.\")\n    print(\"You can view this metric in the Google Cloud Console under Monitoring -> Metrics Explorer.\")\nexcept Exception as e:\n    print(f\"Error writing time series: {e}\")","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade your Python environment to version 3.9 or newer. Ensure your `requirements.txt` or `pyproject.toml` reflects this.","message":"The `google-cloud-monitoring` library version 2.0.0 and later requires Python 3.9 or higher. Older Python versions (3.8 and below) are no longer supported.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Follow Google Cloud's authentication guide for Python, typically using `gcloud auth application-default login` for local development or configuring service accounts/Workload Identity in production. Set the `GOOGLE_CLOUD_PROJECT` environment variable or pass the project ID directly to the client.","message":"Authentication is crucial for interacting with Google Cloud APIs. The client library uses Application Default Credentials (ADC) to find credentials. For local development, you often need to run `gcloud auth application-default login` or set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to a service account key file (though the former is generally preferred). Additionally, the project ID must be provided to the client, either explicitly via `client(project='your-project-id')` or implicitly via the `GOOGLE_CLOUD_PROJECT` environment variable.","severity":"gotcha","affected_versions":"All"},{"fix":"Always define `series.resource.type` and ensure `series.resource.labels` contains the necessary key-value pairs for the chosen resource type, as described in Google Cloud Monitoring documentation for monitored resource types.","message":"When writing custom metrics, it is critical to correctly specify the `MonitoredResource` type and its associated labels. Omitting or providing incorrect resource information can lead to metrics not appearing as expected or performance issues. The `global` resource type is a common fallback for metrics not tied to a specific compute resource, but more specific types (e.g., `gce_instance`, `cloud_run_revision`) are often better.","severity":"gotcha","affected_versions":"All"},{"fix":"Migrate your code to use the `monitoring_v3` module and its specific client classes (e.g., `MetricServiceClient`, `ServiceMonitoringServiceClient`) for the Google Cloud Monitoring API.","message":"Older versions of the `google-cloud-monitoring` library (prior to the 2.x releases) often used `from google.cloud import monitoring` and instantiated `monitoring.Client()`. The current, generated client libraries use `from google.cloud import monitoring_v3` and `monitoring_v3.MetricServiceClient()` (or other specific clients for different Monitoring API services). The older client interface may lack newer API features and is not the recommended approach.","severity":"deprecated","affected_versions":"<2.0.0 (older patterns)"}],"env_vars":null,"last_verified":"2026-05-12T14:22:43.590Z","next_check":"2026-06-26T00:00:00.000Z","problems":[{"fix":"Ensure the Google Cloud Monitoring API is enabled in your Google Cloud project. Grant the required IAM roles (e.g., `roles/monitoring.metricWriter`, `roles/monitoring.viewer`, `roles/monitoring.editor`) to the service account or user in the IAM & Admin section of the Google Cloud Console. For local execution, verify `GOOGLE_APPLICATION_CREDENTIALS` points to a valid service account key with appropriate permissions.","cause":"The service account or user making the API call lacks the necessary IAM permissions, or the Cloud Monitoring API is not enabled for the project.","error":"403 Permission denied (or the resource may not exist)."},{"fix":"Ensure the `google-cloud-monitoring` library is installed and up-to-date by running: `pip install --upgrade google-cloud-monitoring`. If using a virtual environment, ensure it is activated. Consider recreating your virtual environment or checking for conflicting `google-cloud` packages if the issue persists.","cause":"The `google-cloud-monitoring` library is either not installed, installed incorrectly, or an older, incompatible version is being used, or there is a conflict with other `google-cloud` libraries.","error":"ImportError: cannot import name monitoring_v3 from google.cloud"},{"fix":"For `GAUGE` metrics, ensure that each `Point` in a `TimeSeries` has a unique `interval.end_time`. If you need to update a value, submit a new `Point` with a subsequent `end_time`. For `CUMULATIVE` or `DELTA` metrics, ensure the `interval.start_time` and `interval.end_time` are handled correctly according to the metric kind.","cause":"When writing `GAUGE` metric types, you attempted to write multiple data points for the exact same timestamp within a single `create_time_series` request for the same unique combination of metric and monitored resource.","error":"google.api_core.exceptions.InvalidArgument: 400 One or more TimeSeries could not be written: Duplicate TimeSeries encountered."},{"fix":"Use a valid and writable monitored resource type for custom metrics. Common valid types include `global`, `generic_node`, or `generic_task`. Consult the Google Cloud Monitoring documentation for a comprehensive list of supported monitored resource types for custom metrics and select one that best fits your data.","cause":"The `monitored_resource.type` specified when creating a custom metric or writing time series data is not a valid or writable resource type for Cloud Monitoring custom metrics.","error":"google.api_core.exceptions.InvalidArgument: 400 One or more TimeSeries could not be written: Metrics cannot be written to [resource_type]."}],"ecosystem":"pypi","meta_description":null,"install_score":95,"install_tag":"verified","quickstart_score":0,"quickstart_tag":"stale","pypi_latest":null,"install_checks":{"last_tested":"2026-05-12","tag":"verified","tag_description":"installs cleanly on critical runtimes, fast import, recently tested","results":[{"runtime":"python:3.10-alpine","python_version":"3.10","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":2.1,"mem_mb":30.2,"disk_size":"70.2M"},{"runtime":"python:3.10-slim","python_version":"3.10","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":1.06,"mem_mb":23.2,"disk_size":"68M"},{"runtime":"python:3.11-alpine","python_version":"3.11","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":2.81,"mem_mb":31.9,"disk_size":"75.1M"},{"runtime":"python:3.11-slim","python_version":"3.11","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":1.68,"mem_mb":25.4,"disk_size":"73M"},{"runtime":"python:3.12-alpine","python_version":"3.12","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":2.77,"mem_mb":31.6,"disk_size":"66.5M"},{"runtime":"python:3.12-slim","python_version":"3.12","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":2.02,"mem_mb":24.7,"disk_size":"64M"},{"runtime":"python:3.13-alpine","python_version":"3.13","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":2.73,"mem_mb":32,"disk_size":"66.1M"},{"runtime":"python:3.13-slim","python_version":"3.13","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":2.1,"mem_mb":25.6,"disk_size":"64M"},{"runtime":"python:3.9-alpine","python_version":"3.9","os_libc":"alpine (musl)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":1.92,"mem_mb":29.9,"disk_size":"70.3M"},{"runtime":"python:3.9-slim","python_version":"3.9","os_libc":"slim (glibc)","variant":"default","exit_code":0,"wheel_type":null,"failure_reason":null,"install_time_s":null,"import_time_s":1.22,"mem_mb":23,"disk_size":"68M"}]},"quickstart_checks":{"last_tested":"2026-04-23","tag":"stale","tag_description":"widespread failures or data too old to trust","results":[{"runtime":"python:3.10-alpine","exit_code":1},{"runtime":"python:3.10-slim","exit_code":1},{"runtime":"python:3.11-alpine","exit_code":1},{"runtime":"python:3.11-slim","exit_code":1},{"runtime":"python:3.12-alpine","exit_code":1},{"runtime":"python:3.12-slim","exit_code":1},{"runtime":"python:3.13-alpine","exit_code":1},{"runtime":"python:3.13-slim","exit_code":1},{"runtime":"python:3.9-alpine","exit_code":1},{"runtime":"python:3.9-slim","exit_code":1}]}}