Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/logging_v2/services/metrics_service_v2/client.py: 37%
237 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
1# -*- coding: utf-8 -*-
2# Copyright 2023 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16from collections import OrderedDict
17import os
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Sequence,
26 Tuple,
27 Type,
28 Union,
29 cast,
30)
32from google.cloud.logging_v2 import gapic_version as package_version
34from google.api_core import client_options as client_options_lib
35from google.api_core import exceptions as core_exceptions
36from google.api_core import gapic_v1
37from google.api_core import retry as retries
38from google.auth import credentials as ga_credentials # type: ignore
39from google.auth.transport import mtls # type: ignore
40from google.auth.transport.grpc import SslCredentials # type: ignore
41from google.auth.exceptions import MutualTLSChannelError # type: ignore
42from google.oauth2 import service_account # type: ignore
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object] # type: ignore
49from google.api import distribution_pb2 # type: ignore
50from google.api import metric_pb2 # type: ignore
51from google.cloud.logging_v2.services.metrics_service_v2 import pagers
52from google.cloud.logging_v2.types import logging_metrics
53from google.longrunning import operations_pb2 # type: ignore
54from google.protobuf import timestamp_pb2 # type: ignore
55from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
56from .transports.grpc import MetricsServiceV2GrpcTransport
57from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport
60class MetricsServiceV2ClientMeta(type):
61 """Metaclass for the MetricsServiceV2 client.
63 This provides class-level methods for building and retrieving
64 support objects (e.g. transport) without polluting the client instance
65 objects.
66 """
68 _transport_registry = (
69 OrderedDict()
70 ) # type: Dict[str, Type[MetricsServiceV2Transport]]
71 _transport_registry["grpc"] = MetricsServiceV2GrpcTransport
72 _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport
74 def get_transport_class(
75 cls,
76 label: Optional[str] = None,
77 ) -> Type[MetricsServiceV2Transport]:
78 """Returns an appropriate transport class.
80 Args:
81 label: The name of the desired transport. If none is
82 provided, then the first transport in the registry is used.
84 Returns:
85 The transport class to use.
86 """
87 # If a specific transport is requested, return that one.
88 if label:
89 return cls._transport_registry[label]
91 # No transport is requested; return the default (that is, the first one
92 # in the dictionary).
93 return next(iter(cls._transport_registry.values()))
96class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta):
97 """Service for configuring logs-based metrics."""
99 @staticmethod
100 def _get_default_mtls_endpoint(api_endpoint):
101 """Converts api endpoint to mTLS endpoint.
103 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
104 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
105 Args:
106 api_endpoint (Optional[str]): the api endpoint to convert.
107 Returns:
108 str: converted mTLS api endpoint.
109 """
110 if not api_endpoint:
111 return api_endpoint
113 mtls_endpoint_re = re.compile(
114 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
115 )
117 m = mtls_endpoint_re.match(api_endpoint)
118 name, mtls, sandbox, googledomain = m.groups()
119 if mtls or not googledomain:
120 return api_endpoint
122 if sandbox:
123 return api_endpoint.replace(
124 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
125 )
127 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
129 DEFAULT_ENDPOINT = "logging.googleapis.com"
130 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
131 DEFAULT_ENDPOINT
132 )
134 @classmethod
135 def from_service_account_info(cls, info: dict, *args, **kwargs):
136 """Creates an instance of this client using the provided credentials
137 info.
139 Args:
140 info (dict): The service account private key info.
141 args: Additional arguments to pass to the constructor.
142 kwargs: Additional arguments to pass to the constructor.
144 Returns:
145 MetricsServiceV2Client: The constructed client.
146 """
147 credentials = service_account.Credentials.from_service_account_info(info)
148 kwargs["credentials"] = credentials
149 return cls(*args, **kwargs)
151 @classmethod
152 def from_service_account_file(cls, filename: str, *args, **kwargs):
153 """Creates an instance of this client using the provided credentials
154 file.
156 Args:
157 filename (str): The path to the service account private key json
158 file.
159 args: Additional arguments to pass to the constructor.
160 kwargs: Additional arguments to pass to the constructor.
162 Returns:
163 MetricsServiceV2Client: The constructed client.
164 """
165 credentials = service_account.Credentials.from_service_account_file(filename)
166 kwargs["credentials"] = credentials
167 return cls(*args, **kwargs)
169 from_service_account_json = from_service_account_file
171 @property
172 def transport(self) -> MetricsServiceV2Transport:
173 """Returns the transport used by the client instance.
175 Returns:
176 MetricsServiceV2Transport: The transport used by the client
177 instance.
178 """
179 return self._transport
181 @staticmethod
182 def log_metric_path(
183 project: str,
184 metric: str,
185 ) -> str:
186 """Returns a fully-qualified log_metric string."""
187 return "projects/{project}/metrics/{metric}".format(
188 project=project,
189 metric=metric,
190 )
192 @staticmethod
193 def parse_log_metric_path(path: str) -> Dict[str, str]:
194 """Parses a log_metric path into its component segments."""
195 m = re.match(r"^projects/(?P<project>.+?)/metrics/(?P<metric>.+?)$", path)
196 return m.groupdict() if m else {}
198 @staticmethod
199 def common_billing_account_path(
200 billing_account: str,
201 ) -> str:
202 """Returns a fully-qualified billing_account string."""
203 return "billingAccounts/{billing_account}".format(
204 billing_account=billing_account,
205 )
207 @staticmethod
208 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
209 """Parse a billing_account path into its component segments."""
210 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
211 return m.groupdict() if m else {}
213 @staticmethod
214 def common_folder_path(
215 folder: str,
216 ) -> str:
217 """Returns a fully-qualified folder string."""
218 return "folders/{folder}".format(
219 folder=folder,
220 )
222 @staticmethod
223 def parse_common_folder_path(path: str) -> Dict[str, str]:
224 """Parse a folder path into its component segments."""
225 m = re.match(r"^folders/(?P<folder>.+?)$", path)
226 return m.groupdict() if m else {}
228 @staticmethod
229 def common_organization_path(
230 organization: str,
231 ) -> str:
232 """Returns a fully-qualified organization string."""
233 return "organizations/{organization}".format(
234 organization=organization,
235 )
237 @staticmethod
238 def parse_common_organization_path(path: str) -> Dict[str, str]:
239 """Parse a organization path into its component segments."""
240 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
241 return m.groupdict() if m else {}
243 @staticmethod
244 def common_project_path(
245 project: str,
246 ) -> str:
247 """Returns a fully-qualified project string."""
248 return "projects/{project}".format(
249 project=project,
250 )
252 @staticmethod
253 def parse_common_project_path(path: str) -> Dict[str, str]:
254 """Parse a project path into its component segments."""
255 m = re.match(r"^projects/(?P<project>.+?)$", path)
256 return m.groupdict() if m else {}
258 @staticmethod
259 def common_location_path(
260 project: str,
261 location: str,
262 ) -> str:
263 """Returns a fully-qualified location string."""
264 return "projects/{project}/locations/{location}".format(
265 project=project,
266 location=location,
267 )
269 @staticmethod
270 def parse_common_location_path(path: str) -> Dict[str, str]:
271 """Parse a location path into its component segments."""
272 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
273 return m.groupdict() if m else {}
275 @classmethod
276 def get_mtls_endpoint_and_cert_source(
277 cls, client_options: Optional[client_options_lib.ClientOptions] = None
278 ):
279 """Return the API endpoint and client cert source for mutual TLS.
281 The client cert source is determined in the following order:
282 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
283 client cert source is None.
284 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
285 default client cert source exists, use the default one; otherwise the client cert
286 source is None.
288 The API endpoint is determined in the following order:
289 (1) if `client_options.api_endpoint` if provided, use the provided one.
290 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
291 default mTLS endpoint; if the environment variable is "never", use the default API
292 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
293 use the default API endpoint.
295 More details can be found at https://google.aip.dev/auth/4114.
297 Args:
298 client_options (google.api_core.client_options.ClientOptions): Custom options for the
299 client. Only the `api_endpoint` and `client_cert_source` properties may be used
300 in this method.
302 Returns:
303 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
304 client cert source to use.
306 Raises:
307 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
308 """
309 if client_options is None:
310 client_options = client_options_lib.ClientOptions()
311 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
312 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
313 if use_client_cert not in ("true", "false"):
314 raise ValueError(
315 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
316 )
317 if use_mtls_endpoint not in ("auto", "never", "always"):
318 raise MutualTLSChannelError(
319 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
320 )
322 # Figure out the client cert source to use.
323 client_cert_source = None
324 if use_client_cert == "true":
325 if client_options.client_cert_source:
326 client_cert_source = client_options.client_cert_source
327 elif mtls.has_default_client_cert_source():
328 client_cert_source = mtls.default_client_cert_source()
330 # Figure out which api endpoint to use.
331 if client_options.api_endpoint is not None:
332 api_endpoint = client_options.api_endpoint
333 elif use_mtls_endpoint == "always" or (
334 use_mtls_endpoint == "auto" and client_cert_source
335 ):
336 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
337 else:
338 api_endpoint = cls.DEFAULT_ENDPOINT
340 return api_endpoint, client_cert_source
342 def __init__(
343 self,
344 *,
345 credentials: Optional[ga_credentials.Credentials] = None,
346 transport: Optional[Union[str, MetricsServiceV2Transport]] = None,
347 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
348 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
349 ) -> None:
350 """Instantiates the metrics service v2 client.
352 Args:
353 credentials (Optional[google.auth.credentials.Credentials]): The
354 authorization credentials to attach to requests. These
355 credentials identify the application to the service; if none
356 are specified, the client will attempt to ascertain the
357 credentials from the environment.
358 transport (Union[str, MetricsServiceV2Transport]): The
359 transport to use. If set to None, a transport is chosen
360 automatically.
361 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
362 client. It won't take effect if a ``transport`` instance is provided.
363 (1) The ``api_endpoint`` property can be used to override the
364 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
365 environment variable can also be used to override the endpoint:
366 "always" (always use the default mTLS endpoint), "never" (always
367 use the default regular endpoint) and "auto" (auto switch to the
368 default mTLS endpoint if client certificate is present, this is
369 the default value). However, the ``api_endpoint`` property takes
370 precedence if provided.
371 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
372 is "true", then the ``client_cert_source`` property can be used
373 to provide client certificate for mutual TLS transport. If
374 not provided, the default SSL client certificate will be used if
375 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
376 set, no client certificate will be used.
377 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
378 The client info used to send a user-agent string along with
379 API requests. If ``None``, then default info will be used.
380 Generally, you only need to set this if you're developing
381 your own client library.
383 Raises:
384 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
385 creation failed for any reason.
386 """
387 if isinstance(client_options, dict):
388 client_options = client_options_lib.from_dict(client_options)
389 if client_options is None:
390 client_options = client_options_lib.ClientOptions()
391 client_options = cast(client_options_lib.ClientOptions, client_options)
393 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
394 client_options
395 )
397 api_key_value = getattr(client_options, "api_key", None)
398 if api_key_value and credentials:
399 raise ValueError(
400 "client_options.api_key and credentials are mutually exclusive"
401 )
403 # Save or instantiate the transport.
404 # Ordinarily, we provide the transport, but allowing a custom transport
405 # instance provides an extensibility point for unusual situations.
406 if isinstance(transport, MetricsServiceV2Transport):
407 # transport is a MetricsServiceV2Transport instance.
408 if credentials or client_options.credentials_file or api_key_value:
409 raise ValueError(
410 "When providing a transport instance, "
411 "provide its credentials directly."
412 )
413 if client_options.scopes:
414 raise ValueError(
415 "When providing a transport instance, provide its scopes "
416 "directly."
417 )
418 self._transport = transport
419 else:
420 import google.auth._default # type: ignore
422 if api_key_value and hasattr(
423 google.auth._default, "get_api_key_credentials"
424 ):
425 credentials = google.auth._default.get_api_key_credentials(
426 api_key_value
427 )
429 Transport = type(self).get_transport_class(transport)
430 self._transport = Transport(
431 credentials=credentials,
432 credentials_file=client_options.credentials_file,
433 host=api_endpoint,
434 scopes=client_options.scopes,
435 client_cert_source_for_mtls=client_cert_source_func,
436 quota_project_id=client_options.quota_project_id,
437 client_info=client_info,
438 always_use_jwt_access=True,
439 api_audience=client_options.api_audience,
440 )
442 def list_log_metrics(
443 self,
444 request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None,
445 *,
446 parent: Optional[str] = None,
447 retry: OptionalRetry = gapic_v1.method.DEFAULT,
448 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
449 metadata: Sequence[Tuple[str, str]] = (),
450 ) -> pagers.ListLogMetricsPager:
451 r"""Lists logs-based metrics.
453 .. code-block:: python
455 # This snippet has been automatically generated and should be regarded as a
456 # code template only.
457 # It will require modifications to work:
458 # - It may require correct/in-range values for request initialization.
459 # - It may require specifying regional endpoints when creating the service
460 # client as shown in:
461 # https://googleapis.dev/python/google-api-core/latest/client_options.html
462 from google.cloud import logging_v2
464 def sample_list_log_metrics():
465 # Create a client
466 client = logging_v2.MetricsServiceV2Client()
468 # Initialize request argument(s)
469 request = logging_v2.ListLogMetricsRequest(
470 parent="parent_value",
471 )
473 # Make the request
474 page_result = client.list_log_metrics(request=request)
476 # Handle the response
477 for response in page_result:
478 print(response)
480 Args:
481 request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]):
482 The request object. The parameters to ListLogMetrics.
483 parent (str):
484 Required. The name of the project containing the
485 metrics:
487 ::
489 "projects/[PROJECT_ID]"
491 This corresponds to the ``parent`` field
492 on the ``request`` instance; if ``request`` is provided, this
493 should not be set.
494 retry (google.api_core.retry.Retry): Designation of what errors, if any,
495 should be retried.
496 timeout (float): The timeout for this request.
497 metadata (Sequence[Tuple[str, str]]): Strings which should be
498 sent along with the request as metadata.
500 Returns:
501 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager:
502 Result returned from ListLogMetrics.
504 Iterating over this object will yield
505 results and resolve additional pages
506 automatically.
508 """
509 # Create or coerce a protobuf request object.
510 # Quick check: If we got a request object, we should *not* have
511 # gotten any keyword arguments that map to the request.
512 has_flattened_params = any([parent])
513 if request is not None and has_flattened_params:
514 raise ValueError(
515 "If the `request` argument is set, then none of "
516 "the individual field arguments should be set."
517 )
519 # Minor optimization to avoid making a copy if the user passes
520 # in a logging_metrics.ListLogMetricsRequest.
521 # There's no risk of modifying the input as we've already verified
522 # there are no flattened fields.
523 if not isinstance(request, logging_metrics.ListLogMetricsRequest):
524 request = logging_metrics.ListLogMetricsRequest(request)
525 # If we have keyword arguments corresponding to fields on the
526 # request, apply these.
527 if parent is not None:
528 request.parent = parent
530 # Wrap the RPC method; this adds retry and timeout information,
531 # and friendly error handling.
532 rpc = self._transport._wrapped_methods[self._transport.list_log_metrics]
534 # Certain fields should be provided within the metadata header;
535 # add these here.
536 metadata = tuple(metadata) + (
537 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
538 )
540 # Send the request.
541 response = rpc(
542 request,
543 retry=retry,
544 timeout=timeout,
545 metadata=metadata,
546 )
548 # This method is paged; wrap the response in a pager, which provides
549 # an `__iter__` convenience method.
550 response = pagers.ListLogMetricsPager(
551 method=rpc,
552 request=request,
553 response=response,
554 metadata=metadata,
555 )
557 # Done; return the response.
558 return response
560 def get_log_metric(
561 self,
562 request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None,
563 *,
564 metric_name: Optional[str] = None,
565 retry: OptionalRetry = gapic_v1.method.DEFAULT,
566 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
567 metadata: Sequence[Tuple[str, str]] = (),
568 ) -> logging_metrics.LogMetric:
569 r"""Gets a logs-based metric.
571 .. code-block:: python
573 # This snippet has been automatically generated and should be regarded as a
574 # code template only.
575 # It will require modifications to work:
576 # - It may require correct/in-range values for request initialization.
577 # - It may require specifying regional endpoints when creating the service
578 # client as shown in:
579 # https://googleapis.dev/python/google-api-core/latest/client_options.html
580 from google.cloud import logging_v2
582 def sample_get_log_metric():
583 # Create a client
584 client = logging_v2.MetricsServiceV2Client()
586 # Initialize request argument(s)
587 request = logging_v2.GetLogMetricRequest(
588 metric_name="metric_name_value",
589 )
591 # Make the request
592 response = client.get_log_metric(request=request)
594 # Handle the response
595 print(response)
597 Args:
598 request (Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]):
599 The request object. The parameters to GetLogMetric.
600 metric_name (str):
601 Required. The resource name of the desired metric:
603 ::
605 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
607 This corresponds to the ``metric_name`` field
608 on the ``request`` instance; if ``request`` is provided, this
609 should not be set.
610 retry (google.api_core.retry.Retry): Designation of what errors, if any,
611 should be retried.
612 timeout (float): The timeout for this request.
613 metadata (Sequence[Tuple[str, str]]): Strings which should be
614 sent along with the request as metadata.
616 Returns:
617 google.cloud.logging_v2.types.LogMetric:
618 Describes a logs-based metric. The
619 value of the metric is the number of log
620 entries that match a logs filter in a
621 given time interval.
623 Logs-based metrics can also be used to
624 extract values from logs and create a
625 distribution of the values. The
626 distribution records the statistics of
627 the extracted values along with an
628 optional histogram of the values as
629 specified by the bucket options.
631 """
632 # Create or coerce a protobuf request object.
633 # Quick check: If we got a request object, we should *not* have
634 # gotten any keyword arguments that map to the request.
635 has_flattened_params = any([metric_name])
636 if request is not None and has_flattened_params:
637 raise ValueError(
638 "If the `request` argument is set, then none of "
639 "the individual field arguments should be set."
640 )
642 # Minor optimization to avoid making a copy if the user passes
643 # in a logging_metrics.GetLogMetricRequest.
644 # There's no risk of modifying the input as we've already verified
645 # there are no flattened fields.
646 if not isinstance(request, logging_metrics.GetLogMetricRequest):
647 request = logging_metrics.GetLogMetricRequest(request)
648 # If we have keyword arguments corresponding to fields on the
649 # request, apply these.
650 if metric_name is not None:
651 request.metric_name = metric_name
653 # Wrap the RPC method; this adds retry and timeout information,
654 # and friendly error handling.
655 rpc = self._transport._wrapped_methods[self._transport.get_log_metric]
657 # Certain fields should be provided within the metadata header;
658 # add these here.
659 metadata = tuple(metadata) + (
660 gapic_v1.routing_header.to_grpc_metadata(
661 (("metric_name", request.metric_name),)
662 ),
663 )
665 # Send the request.
666 response = rpc(
667 request,
668 retry=retry,
669 timeout=timeout,
670 metadata=metadata,
671 )
673 # Done; return the response.
674 return response
676 def create_log_metric(
677 self,
678 request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None,
679 *,
680 parent: Optional[str] = None,
681 metric: Optional[logging_metrics.LogMetric] = None,
682 retry: OptionalRetry = gapic_v1.method.DEFAULT,
683 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
684 metadata: Sequence[Tuple[str, str]] = (),
685 ) -> logging_metrics.LogMetric:
686 r"""Creates a logs-based metric.
688 .. code-block:: python
690 # This snippet has been automatically generated and should be regarded as a
691 # code template only.
692 # It will require modifications to work:
693 # - It may require correct/in-range values for request initialization.
694 # - It may require specifying regional endpoints when creating the service
695 # client as shown in:
696 # https://googleapis.dev/python/google-api-core/latest/client_options.html
697 from google.cloud import logging_v2
699 def sample_create_log_metric():
700 # Create a client
701 client = logging_v2.MetricsServiceV2Client()
703 # Initialize request argument(s)
704 metric = logging_v2.LogMetric()
705 metric.name = "name_value"
706 metric.filter = "filter_value"
708 request = logging_v2.CreateLogMetricRequest(
709 parent="parent_value",
710 metric=metric,
711 )
713 # Make the request
714 response = client.create_log_metric(request=request)
716 # Handle the response
717 print(response)
719 Args:
720 request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]):
721 The request object. The parameters to CreateLogMetric.
722 parent (str):
723 Required. The resource name of the project in which to
724 create the metric:
726 ::
728 "projects/[PROJECT_ID]"
730 The new metric must be provided in the request.
732 This corresponds to the ``parent`` field
733 on the ``request`` instance; if ``request`` is provided, this
734 should not be set.
735 metric (google.cloud.logging_v2.types.LogMetric):
736 Required. The new logs-based metric,
737 which must not have an identifier that
738 already exists.
740 This corresponds to the ``metric`` field
741 on the ``request`` instance; if ``request`` is provided, this
742 should not be set.
743 retry (google.api_core.retry.Retry): Designation of what errors, if any,
744 should be retried.
745 timeout (float): The timeout for this request.
746 metadata (Sequence[Tuple[str, str]]): Strings which should be
747 sent along with the request as metadata.
749 Returns:
750 google.cloud.logging_v2.types.LogMetric:
751 Describes a logs-based metric. The
752 value of the metric is the number of log
753 entries that match a logs filter in a
754 given time interval.
756 Logs-based metrics can also be used to
757 extract values from logs and create a
758 distribution of the values. The
759 distribution records the statistics of
760 the extracted values along with an
761 optional histogram of the values as
762 specified by the bucket options.
764 """
765 # Create or coerce a protobuf request object.
766 # Quick check: If we got a request object, we should *not* have
767 # gotten any keyword arguments that map to the request.
768 has_flattened_params = any([parent, metric])
769 if request is not None and has_flattened_params:
770 raise ValueError(
771 "If the `request` argument is set, then none of "
772 "the individual field arguments should be set."
773 )
775 # Minor optimization to avoid making a copy if the user passes
776 # in a logging_metrics.CreateLogMetricRequest.
777 # There's no risk of modifying the input as we've already verified
778 # there are no flattened fields.
779 if not isinstance(request, logging_metrics.CreateLogMetricRequest):
780 request = logging_metrics.CreateLogMetricRequest(request)
781 # If we have keyword arguments corresponding to fields on the
782 # request, apply these.
783 if parent is not None:
784 request.parent = parent
785 if metric is not None:
786 request.metric = metric
788 # Wrap the RPC method; this adds retry and timeout information,
789 # and friendly error handling.
790 rpc = self._transport._wrapped_methods[self._transport.create_log_metric]
792 # Certain fields should be provided within the metadata header;
793 # add these here.
794 metadata = tuple(metadata) + (
795 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
796 )
798 # Send the request.
799 response = rpc(
800 request,
801 retry=retry,
802 timeout=timeout,
803 metadata=metadata,
804 )
806 # Done; return the response.
807 return response
809 def update_log_metric(
810 self,
811 request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None,
812 *,
813 metric_name: Optional[str] = None,
814 metric: Optional[logging_metrics.LogMetric] = None,
815 retry: OptionalRetry = gapic_v1.method.DEFAULT,
816 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
817 metadata: Sequence[Tuple[str, str]] = (),
818 ) -> logging_metrics.LogMetric:
819 r"""Creates or updates a logs-based metric.
821 .. code-block:: python
823 # This snippet has been automatically generated and should be regarded as a
824 # code template only.
825 # It will require modifications to work:
826 # - It may require correct/in-range values for request initialization.
827 # - It may require specifying regional endpoints when creating the service
828 # client as shown in:
829 # https://googleapis.dev/python/google-api-core/latest/client_options.html
830 from google.cloud import logging_v2
832 def sample_update_log_metric():
833 # Create a client
834 client = logging_v2.MetricsServiceV2Client()
836 # Initialize request argument(s)
837 metric = logging_v2.LogMetric()
838 metric.name = "name_value"
839 metric.filter = "filter_value"
841 request = logging_v2.UpdateLogMetricRequest(
842 metric_name="metric_name_value",
843 metric=metric,
844 )
846 # Make the request
847 response = client.update_log_metric(request=request)
849 # Handle the response
850 print(response)
852 Args:
853 request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]):
854 The request object. The parameters to UpdateLogMetric.
855 metric_name (str):
856 Required. The resource name of the metric to update:
858 ::
860 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
862 The updated metric must be provided in the request and
863 it's ``name`` field must be the same as ``[METRIC_ID]``
864 If the metric does not exist in ``[PROJECT_ID]``, then a
865 new metric is created.
867 This corresponds to the ``metric_name`` field
868 on the ``request`` instance; if ``request`` is provided, this
869 should not be set.
870 metric (google.cloud.logging_v2.types.LogMetric):
871 Required. The updated metric.
872 This corresponds to the ``metric`` field
873 on the ``request`` instance; if ``request`` is provided, this
874 should not be set.
875 retry (google.api_core.retry.Retry): Designation of what errors, if any,
876 should be retried.
877 timeout (float): The timeout for this request.
878 metadata (Sequence[Tuple[str, str]]): Strings which should be
879 sent along with the request as metadata.
881 Returns:
882 google.cloud.logging_v2.types.LogMetric:
883 Describes a logs-based metric. The
884 value of the metric is the number of log
885 entries that match a logs filter in a
886 given time interval.
888 Logs-based metrics can also be used to
889 extract values from logs and create a
890 distribution of the values. The
891 distribution records the statistics of
892 the extracted values along with an
893 optional histogram of the values as
894 specified by the bucket options.
896 """
897 # Create or coerce a protobuf request object.
898 # Quick check: If we got a request object, we should *not* have
899 # gotten any keyword arguments that map to the request.
900 has_flattened_params = any([metric_name, metric])
901 if request is not None and has_flattened_params:
902 raise ValueError(
903 "If the `request` argument is set, then none of "
904 "the individual field arguments should be set."
905 )
907 # Minor optimization to avoid making a copy if the user passes
908 # in a logging_metrics.UpdateLogMetricRequest.
909 # There's no risk of modifying the input as we've already verified
910 # there are no flattened fields.
911 if not isinstance(request, logging_metrics.UpdateLogMetricRequest):
912 request = logging_metrics.UpdateLogMetricRequest(request)
913 # If we have keyword arguments corresponding to fields on the
914 # request, apply these.
915 if metric_name is not None:
916 request.metric_name = metric_name
917 if metric is not None:
918 request.metric = metric
920 # Wrap the RPC method; this adds retry and timeout information,
921 # and friendly error handling.
922 rpc = self._transport._wrapped_methods[self._transport.update_log_metric]
924 # Certain fields should be provided within the metadata header;
925 # add these here.
926 metadata = tuple(metadata) + (
927 gapic_v1.routing_header.to_grpc_metadata(
928 (("metric_name", request.metric_name),)
929 ),
930 )
932 # Send the request.
933 response = rpc(
934 request,
935 retry=retry,
936 timeout=timeout,
937 metadata=metadata,
938 )
940 # Done; return the response.
941 return response
943 def delete_log_metric(
944 self,
945 request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None,
946 *,
947 metric_name: Optional[str] = None,
948 retry: OptionalRetry = gapic_v1.method.DEFAULT,
949 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
950 metadata: Sequence[Tuple[str, str]] = (),
951 ) -> None:
952 r"""Deletes a logs-based metric.
954 .. code-block:: python
956 # This snippet has been automatically generated and should be regarded as a
957 # code template only.
958 # It will require modifications to work:
959 # - It may require correct/in-range values for request initialization.
960 # - It may require specifying regional endpoints when creating the service
961 # client as shown in:
962 # https://googleapis.dev/python/google-api-core/latest/client_options.html
963 from google.cloud import logging_v2
965 def sample_delete_log_metric():
966 # Create a client
967 client = logging_v2.MetricsServiceV2Client()
969 # Initialize request argument(s)
970 request = logging_v2.DeleteLogMetricRequest(
971 metric_name="metric_name_value",
972 )
974 # Make the request
975 client.delete_log_metric(request=request)
977 Args:
978 request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]):
979 The request object. The parameters to DeleteLogMetric.
980 metric_name (str):
981 Required. The resource name of the metric to delete:
983 ::
985 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
987 This corresponds to the ``metric_name`` field
988 on the ``request`` instance; if ``request`` is provided, this
989 should not be set.
990 retry (google.api_core.retry.Retry): Designation of what errors, if any,
991 should be retried.
992 timeout (float): The timeout for this request.
993 metadata (Sequence[Tuple[str, str]]): Strings which should be
994 sent along with the request as metadata.
995 """
996 # Create or coerce a protobuf request object.
997 # Quick check: If we got a request object, we should *not* have
998 # gotten any keyword arguments that map to the request.
999 has_flattened_params = any([metric_name])
1000 if request is not None and has_flattened_params:
1001 raise ValueError(
1002 "If the `request` argument is set, then none of "
1003 "the individual field arguments should be set."
1004 )
1006 # Minor optimization to avoid making a copy if the user passes
1007 # in a logging_metrics.DeleteLogMetricRequest.
1008 # There's no risk of modifying the input as we've already verified
1009 # there are no flattened fields.
1010 if not isinstance(request, logging_metrics.DeleteLogMetricRequest):
1011 request = logging_metrics.DeleteLogMetricRequest(request)
1012 # If we have keyword arguments corresponding to fields on the
1013 # request, apply these.
1014 if metric_name is not None:
1015 request.metric_name = metric_name
1017 # Wrap the RPC method; this adds retry and timeout information,
1018 # and friendly error handling.
1019 rpc = self._transport._wrapped_methods[self._transport.delete_log_metric]
1021 # Certain fields should be provided within the metadata header;
1022 # add these here.
1023 metadata = tuple(metadata) + (
1024 gapic_v1.routing_header.to_grpc_metadata(
1025 (("metric_name", request.metric_name),)
1026 ),
1027 )
1029 # Send the request.
1030 rpc(
1031 request,
1032 retry=retry,
1033 timeout=timeout,
1034 metadata=metadata,
1035 )
1037 def __enter__(self) -> "MetricsServiceV2Client":
1038 return self
1040 def __exit__(self, type, value, traceback):
1041 """Releases underlying transport's resources.
1043 .. warning::
1044 ONLY use as a context manager if the transport is NOT shared
1045 with other clients! Exiting the with block will CLOSE the transport
1046 and may cause errors in other clients!
1047 """
1048 self.transport.close()
1050 def list_operations(
1051 self,
1052 request: Optional[operations_pb2.ListOperationsRequest] = None,
1053 *,
1054 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1055 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1056 metadata: Sequence[Tuple[str, str]] = (),
1057 ) -> operations_pb2.ListOperationsResponse:
1058 r"""Lists operations that match the specified filter in the request.
1060 Args:
1061 request (:class:`~.operations_pb2.ListOperationsRequest`):
1062 The request object. Request message for
1063 `ListOperations` method.
1064 retry (google.api_core.retry.Retry): Designation of what errors,
1065 if any, should be retried.
1066 timeout (float): The timeout for this request.
1067 metadata (Sequence[Tuple[str, str]]): Strings which should be
1068 sent along with the request as metadata.
1069 Returns:
1070 ~.operations_pb2.ListOperationsResponse:
1071 Response message for ``ListOperations`` method.
1072 """
1073 # Create or coerce a protobuf request object.
1074 # The request isn't a proto-plus wrapped type,
1075 # so it must be constructed via keyword expansion.
1076 if isinstance(request, dict):
1077 request = operations_pb2.ListOperationsRequest(**request)
1079 # Wrap the RPC method; this adds retry and timeout information,
1080 # and friendly error handling.
1081 rpc = gapic_v1.method.wrap_method(
1082 self._transport.list_operations,
1083 default_timeout=None,
1084 client_info=DEFAULT_CLIENT_INFO,
1085 )
1087 # Certain fields should be provided within the metadata header;
1088 # add these here.
1089 metadata = tuple(metadata) + (
1090 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1091 )
1093 # Send the request.
1094 response = rpc(
1095 request,
1096 retry=retry,
1097 timeout=timeout,
1098 metadata=metadata,
1099 )
1101 # Done; return the response.
1102 return response
1104 def get_operation(
1105 self,
1106 request: Optional[operations_pb2.GetOperationRequest] = None,
1107 *,
1108 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1109 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1110 metadata: Sequence[Tuple[str, str]] = (),
1111 ) -> operations_pb2.Operation:
1112 r"""Gets the latest state of a long-running operation.
1114 Args:
1115 request (:class:`~.operations_pb2.GetOperationRequest`):
1116 The request object. Request message for
1117 `GetOperation` method.
1118 retry (google.api_core.retry.Retry): Designation of what errors,
1119 if any, should be retried.
1120 timeout (float): The timeout for this request.
1121 metadata (Sequence[Tuple[str, str]]): Strings which should be
1122 sent along with the request as metadata.
1123 Returns:
1124 ~.operations_pb2.Operation:
1125 An ``Operation`` object.
1126 """
1127 # Create or coerce a protobuf request object.
1128 # The request isn't a proto-plus wrapped type,
1129 # so it must be constructed via keyword expansion.
1130 if isinstance(request, dict):
1131 request = operations_pb2.GetOperationRequest(**request)
1133 # Wrap the RPC method; this adds retry and timeout information,
1134 # and friendly error handling.
1135 rpc = gapic_v1.method.wrap_method(
1136 self._transport.get_operation,
1137 default_timeout=None,
1138 client_info=DEFAULT_CLIENT_INFO,
1139 )
1141 # Certain fields should be provided within the metadata header;
1142 # add these here.
1143 metadata = tuple(metadata) + (
1144 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1145 )
1147 # Send the request.
1148 response = rpc(
1149 request,
1150 retry=retry,
1151 timeout=timeout,
1152 metadata=metadata,
1153 )
1155 # Done; return the response.
1156 return response
1158 def cancel_operation(
1159 self,
1160 request: Optional[operations_pb2.CancelOperationRequest] = None,
1161 *,
1162 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1163 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1164 metadata: Sequence[Tuple[str, str]] = (),
1165 ) -> None:
1166 r"""Starts asynchronous cancellation on a long-running operation.
1168 The server makes a best effort to cancel the operation, but success
1169 is not guaranteed. If the server doesn't support this method, it returns
1170 `google.rpc.Code.UNIMPLEMENTED`.
1172 Args:
1173 request (:class:`~.operations_pb2.CancelOperationRequest`):
1174 The request object. Request message for
1175 `CancelOperation` method.
1176 retry (google.api_core.retry.Retry): Designation of what errors,
1177 if any, should be retried.
1178 timeout (float): The timeout for this request.
1179 metadata (Sequence[Tuple[str, str]]): Strings which should be
1180 sent along with the request as metadata.
1181 Returns:
1182 None
1183 """
1184 # Create or coerce a protobuf request object.
1185 # The request isn't a proto-plus wrapped type,
1186 # so it must be constructed via keyword expansion.
1187 if isinstance(request, dict):
1188 request = operations_pb2.CancelOperationRequest(**request)
1190 # Wrap the RPC method; this adds retry and timeout information,
1191 # and friendly error handling.
1192 rpc = gapic_v1.method.wrap_method(
1193 self._transport.cancel_operation,
1194 default_timeout=None,
1195 client_info=DEFAULT_CLIENT_INFO,
1196 )
1198 # Certain fields should be provided within the metadata header;
1199 # add these here.
1200 metadata = tuple(metadata) + (
1201 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1202 )
1204 # Send the request.
1205 rpc(
1206 request,
1207 retry=retry,
1208 timeout=timeout,
1209 metadata=metadata,
1210 )
1213DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1214 gapic_version=package_version.__version__
1215)
1218__all__ = ("MetricsServiceV2Client",)