Skip to content

Instantly share code, notes, and snippets.

@jonascheng
Created May 16, 2018 02:28
Show Gist options
  • Select an option

  • Save jonascheng/b5c1cbf5cab2f43ec69b2179dd9dea29 to your computer and use it in GitHub Desktop.

Select an option

Save jonascheng/b5c1cbf5cab2f43ec69b2179dd9dea29 to your computer and use it in GitHub Desktop.
Sample code to list_time_series from GCP Pub/Sub
# export GOOGLE_APPLICATION_CREDENTIALS='credential file in JSON'
import arrow
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import enums
from google.cloud.monitoring_v3.types import TimeInterval, Aggregation
from google.api_core import exceptions
client = monitoring_v3.MetricServiceClient()
# your project name
name = client.project_path('soocii-backend')
end_time = arrow.utcnow()
# lookback one minute
start_time = end_time.shift(minutes=-1)
interval = TimeInterval()
interval.start_time.FromDatetime(start_time.naive)
interval.end_time.FromDatetime(end_time.naive)
view = enums.ListTimeSeriesRequest.TimeSeriesView.FULL
# 每五分鐘平均
aggregation = Aggregation(
per_series_aligner='ALIGN_MEAN',
alignment_period={'seconds': 5*60}
)
# Iterate over all results
for d in client.list_metric_descriptors(name):
if 'pubsub' in d.type:
# if 'pubsub.googleapis.com/subscription/backlog_bytes' in d.type:
filter_ = 'metric.type="{}" AND resource.labels.subscription_id="thor-staging-mission-accounting-sub"'.format(d.type)
try:
values = client.list_time_series(name, filter_, interval, view)
# values = client.list_time_series(name, filter_, interval, view, aggregation)
for v in values:
print('Descriptor: {}'.format(d))
print('Value: {}'.format(v))
except exceptions.InvalidArgument as e:
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment