Stackdriver Monitoring Client#

Client for interacting with the Google Stackdriver Monitoring API (V3).

Example:

>>> from google.cloud import monitoring
>>> client = monitoring.Client()
>>> query = client.query(minutes=5)
>>> print(query.as_dataframe())  # Requires pandas.

At present, the client supports querying of time series, metric descriptors, and monitored resource descriptors.

class google.cloud.monitoring.client.Client(project=None, credentials=None, _http=None)[source]#

Bases: google.cloud.client.ClientWithProject

Client to bundle configuration needed for API requests.

Parameters:
  • project (str) – The target project. If not passed, falls back to the default inferred from the environment.
  • credentials (Credentials) – (Optional) The OAuth2 Credentials to use for this client. If not passed (and if no _http object is passed), falls back to the default inferred from the environment.
  • _http (Http) – (Optional) HTTP object to make requests. Can be any object that defines request() with the same interface as request(). If not passed, an _http object is created that is bound to the credentials for the current object. This parameter should be considered private, and could change in the future.
SCOPE = ('https://www.googleapis.com/auth/monitoring.read', 'https://www.googleapis.com/auth/monitoring', 'https://www.googleapis.com/auth/cloud-platform')#

The scopes required for authenticating as a Monitoring consumer.

fetch_group(group_id)[source]#

Fetch a group from the API based on it’s ID.

Example:

>>> try:
>>>     group = client.fetch_group('1234')
>>> except google.cloud.exceptions.NotFound:
>>>     print('That group does not exist!')
Parameters:group_id (str) – The ID of the group.
Return type:Group
Returns:The group instance.
Raises:google.cloud.exceptions.NotFound if the group is not found.
fetch_metric_descriptor(metric_type)[source]#

Look up a metric descriptor by type.

Example:

>>> METRIC = 'compute.googleapis.com/instance/cpu/utilization'
>>> print(client.fetch_metric_descriptor(METRIC))
Parameters:metric_type (str) – The metric type name.
Return type:MetricDescriptor
Returns:The metric descriptor instance.
Raises:google.cloud.exceptions.NotFound if the metric descriptor is not found.
fetch_resource_descriptor(resource_type)[source]#

Look up a monitored resource descriptor by type.

Example:

>>> print(client.fetch_resource_descriptor('gce_instance'))
Parameters:resource_type (str) – The resource type name.
Return type:ResourceDescriptor
Returns:The resource descriptor instance.
Raises:google.cloud.exceptions.NotFound if the resource descriptor is not found.
group(group_id=None, display_name=None, parent_id=None, filter_string=None, is_cluster=False)[source]#

Factory constructor for group object.

Note

This will not make an HTTP request; it simply instantiates a group object owned by this client.

Parameters:
  • group_id (str) – (Optional) The ID of the group.
  • display_name (str) – (Optional) A user-assigned name for this group, used only for display purposes.
  • parent_id (str) – (Optional) The ID of the group’s parent, if it has one.
  • filter_string (str) – (Optional) The filter string used to determine which monitored resources belong to this group.
  • is_cluster (bool) – If true, the members of this group are considered to be a cluster. The system can perform additional analysis on groups that are clusters.
Return type:

Group

Returns:

The group created with the passed-in arguments.

Raises:

ValueError if both group_id and name are specified.

list_groups()[source]#

List all groups for the project.

Example:

>>> for group in client.list_groups():
...     print((group.display_name, group.name))
Return type:list of Group
Returns:A list of group instances.
list_metric_descriptors(filter_string=None, type_prefix=None)[source]#

List all metric descriptors for the project.

Examples:

>>> for descriptor in client.list_metric_descriptors():
...     print(descriptor.type)

>>> for descriptor in client.list_metric_descriptors(
...         type_prefix='custom.'):
...     print(descriptor.type)
Parameters:
  • filter_string (str) – (Optional) An optional filter expression describing the metric descriptors to be returned. See the filter documentation.
  • type_prefix (str) – (Optional) An optional prefix constraining the selected metric types. This adds metric.type = starts_with("<prefix>") to the filter.
Return type:

list of MetricDescriptor

Returns:

A list of metric descriptor instances.

list_resource_descriptors(filter_string=None)[source]#

List all monitored resource descriptors for the project.

Example:

>>> for descriptor in client.list_resource_descriptors():
...     print(descriptor.type)
Parameters:filter_string (str) – (Optional) An optional filter expression describing the resource descriptors to be returned. See the filter documentation.
Return type:list of ResourceDescriptor
Returns:A list of resource descriptor instances.
static metric(type_, labels)[source]#

Factory for constructing metric objects.

Metric objects are typically created to write custom metric values. The type should match the metric type specified in the MetricDescriptor used to create the custom metric:

>>> metric = client.metric('custom.googleapis.com/my_metric',
...                        labels={
...                            'status': 'successful',
...                         })
Parameters:
  • type (str) – The metric type name.
  • labels (dict) – A mapping from label names to values for all labels enumerated in the associated MetricDescriptor.
Return type:

Metric

Returns:

The metric object.

metric_descriptor(type_, metric_kind='METRIC_KIND_UNSPECIFIED', value_type='VALUE_TYPE_UNSPECIFIED', labels=(), unit='', description='', display_name='')[source]#

Construct a metric descriptor object.

Metric descriptors specify the schema for a particular metric type.

This factory method is used most often in conjunction with the metric descriptor create() method to define custom metrics:

>>> descriptor = client.metric_descriptor(
...     'custom.googleapis.com/my_metric',
...     metric_kind=MetricKind.GAUGE,
...     value_type=ValueType.DOUBLE,
...     description='This is a simple example of a custom metric.')
>>> descriptor.create()

Here is an example where the custom metric is parameterized by a metric label:

>>> label = LabelDescriptor('response_code', LabelValueType.INT64,
...                         description='HTTP status code')
>>> descriptor = client.metric_descriptor(
...     'custom.googleapis.com/my_app/response_count',
...     metric_kind=MetricKind.CUMULATIVE,
...     value_type=ValueType.INT64,
...     labels=[label],
...     description='Cumulative count of HTTP responses.')
>>> descriptor.create()
Parameters:
  • type (str) – The metric type including a DNS name prefix. For example: "custom.googleapis.com/my_metric"
  • metric_kind (str) – The kind of measurement. It must be one of MetricKind.GAUGE, MetricKind.DELTA, or MetricKind.CUMULATIVE. See MetricKind.
  • value_type (str) – The value type of the metric. It must be one of ValueType.BOOL, ValueType.INT64, ValueType.DOUBLE, ValueType.STRING, or ValueType.DISTRIBUTION. See ValueType.
  • labels (list of LabelDescriptor) – A sequence of zero or more label descriptors specifying the labels used to identify a specific instance of this metric.
  • unit (str) – An optional unit in which the metric value is reported.
  • description (str) – An optional detailed description of the metric.
  • display_name (str) – An optional concise name for the metric.
Return type:

MetricDescriptor

Returns:

The metric descriptor created with the passed-in arguments.

query(metric_type='compute.googleapis.com/instance/cpu/utilization', end_time=None, days=0, hours=0, minutes=0)[source]#

Construct a query object for retrieving metric data.

Example:

>>> query = client.query(minutes=5)
>>> print(query.as_dataframe())  # Requires pandas.
Parameters:
  • metric_type (str) – The metric type name. The default value is Query.DEFAULT_METRIC_TYPE, but please note that this default value is provided only for demonstration purposes and is subject to change. See the supported metrics.
  • end_time (datetime.datetime) –

    (Optional) The end time (inclusive) of the time interval for which results should be returned, as a datetime object. The default is the start of the current minute.

    The start time (exclusive) is determined by combining the values of days, hours, and minutes, and subtracting the resulting duration from the end time.

    It is also allowed to omit the end time and duration here, in which case select_interval() must be called before the query is executed.

  • days (int) – The number of days in the time interval.
  • hours (int) – The number of hours in the time interval.
  • minutes (int) – The number of minutes in the time interval.
Return type:

Query

Returns:

The query object.

Raises:

ValueError if end_time is specified but days, hours, and minutes are all zero. If you really want to specify a point in time, use select_interval().

static resource(type_, labels)[source]#

Factory for constructing monitored resource objects.

A monitored resource object ( Resource) is typically used to create a TimeSeries object.

For a list of possible monitored resource types and their associated labels, see:

https://cloud.google.com/monitoring/api/resources

Parameters:
  • type (str) – The monitored resource type name.
  • labels (dict) – A mapping from label names to values for all labels enumerated in the associated ResourceDescriptor, except that project_id can and should be omitted when writing time series data.
Return type:

Resource

Returns:

A monitored resource object.

static time_series(metric, resource, value, end_time=None, start_time=None)[source]#

Construct a time series object for a single data point.

Note

While TimeSeries objects returned by the API typically have multiple data points, TimeSeries objects sent to the API must have at most one point.

For example:

>>> timeseries = client.time_series(metric, resource, 1.23,
...                                 end_time=end)

For more information, see:

https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries

Parameters:
  • metric (Metric) – A Metric.
  • resource (Resource) – A Resource object.
  • value (bool, int, string, or float) –

    The value of the data point to create for the TimeSeries.

    Note

    The Python type of the value will determine the ValueType sent to the API, which must match the value type specified in the metric descriptor. For example, a Python float will be sent to the API as a ValueType.DOUBLE.

  • end_time (datetime) – The end time for the point to be included in the time series. Assumed to be UTC if no time zone information is present. Defaults to the current time, as obtained by calling datetime.datetime.utcnow().
  • start_time (datetime) – The start time for the point to be included in the time series. Assumed to be UTC if no time zone information is present. Defaults to None. If the start time is unspecified, the API interprets the start time to be the same as the end time.
Return type:

TimeSeries

Returns:

A time series object.

write_point(metric, resource, value, end_time=None, start_time=None)[source]#

Write a single point for a metric to the API.

This is a convenience method to write a single time series object to the API. To write multiple time series objects to the API as a batch operation, use the time_series() factory method to create time series objects and the write_time_series() method to write the objects.

Example:

>>> client.write_point(metric, resource, 3.14)
Parameters:
  • metric (Metric) – A Metric object.
  • resource (Resource) – A Resource object.
  • value (bool, int, string, or float) –

    The value of the data point to create for the TimeSeries.

    Note

    The Python type of the value will determine the ValueType sent to the API, which must match the value type specified in the metric descriptor. For example, a Python float will be sent to the API as a ValueType.DOUBLE.

  • end_time (datetime) – The end time for the point to be included in the time series. Assumed to be UTC if no time zone information is present. Defaults to the current time, as obtained by calling datetime.datetime.utcnow().
  • start_time (datetime) – The start time for the point to be included in the time series. Assumed to be UTC if no time zone information is present. Defaults to None. If the start time is unspecified, the API interprets the start time to be the same as the end time.
write_time_series(timeseries_list)[source]#

Write a list of time series objects to the API.

The recommended approach to creating time series objects is using the time_series() factory method.

Example:

>>> client.write_time_series([ts1, ts2])

If you only need to write a single time series object, consider using the write_point() method instead.

Parameters:timeseries_list (list of TimeSeries) – A list of time series object to be written to the API. Each time series must contain exactly one point.