Skip to content

Instantly share code, notes, and snippets.

@winter-code
Last active July 26, 2021 07:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winter-code/d982145ff709b0765d6ea9d0188670b4 to your computer and use it in GitHub Desktop.
Save winter-code/d982145ff709b0765d6ea9d0188670b4 to your computer and use it in GitHub Desktop.
Writing metric data to custom metrics on gcp monitoring dashboards
from google.cloud import monitoring_v3
import time
client = monitoring_v3.MetricServiceClient()
project_id = 'your-project-id' #TODO: Replace with yours
project_name = f"projects/{project_id}"
series = monitoring_v3.TimeSeries()
series.metric.type = "custom.googleapis.com/my_metric"
series.resource.type = "gce_instance"
series.resource.labels["instance_id"] = "2689951889123686840"
series.resource.labels["zone"] = "us-west1-b"
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.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment