Created
August 11, 2021 21:43
-
-
Save ZaxR/a83a5951ff9dcc2f2b5be79721d83aa9 to your computer and use it in GitHub Desktop.
Google Monitoring: Write a Custom Metric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
!pip install --upgrade google-cloud-monitoring | |
from google.cloud import monitoring_v3 | |
import time | |
def create_custom_ts(metric_name="my_metric"): | |
series = monitoring_v3.TimeSeries() | |
# https://cloud.google.com/monitoring/custom-metrics/creating-metrics | |
series.metric.type = f"custom.googleapis.com/{metric_name}" | |
# A common practice is to use the monitored resource objects that represent the physical resources where your application code is running | |
# The resource labels varies by type, but are documented poorly | |
series.resource.type = "gce_instance" | |
series.resource.labels["instance_id"] = "1234567890123456789" | |
series.resource.labels["zone"] = "us-central1-f" | |
return series | |
def log_ts_metric(value, project): | |
ts = create_custom_ts() | |
now = time.time() | |
seconds = int(now) | |
nanos = int((now - seconds) * 10 ** 9) | |
interval = monitoring_v3.TimeInterval( | |
{"end_time": {"seconds": seconds, "nanos": nanos}} | |
) | |
points = [monitoring_v3.Point({"interval": interval, "value": {"double_value": value}})] | |
ts.points = points | |
client = monitoring_v3.MetricServiceClient() | |
client.create_time_series(request={"name": f"projects/{project}", "time_series": [ts]}) | |
print("Successfully wrote time series.") | |
log_ts_metric(value=3) | |
log_ts_metric(value=2) | |
log_ts_metric(value=2.3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment