1# -*- coding: utf-8 -*-
2# Copyright 2025 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#
16import logging as std_logging
17from collections import OrderedDict
18import re
19from typing import (
20 Dict,
21 Callable,
22 Mapping,
23 MutableMapping,
24 MutableSequence,
25 Optional,
26 Sequence,
27 Tuple,
28 Type,
29 Union,
30)
31
32from google.cloud.logging_v2 import gapic_version as package_version
33
34from google.api_core.client_options import ClientOptions
35from google.api_core import exceptions as core_exceptions
36from google.api_core import gapic_v1
37from google.api_core import retry_async as retries
38from google.auth import credentials as ga_credentials # type: ignore
39from google.oauth2 import service_account # type: ignore
40
41
42try:
43 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
44except AttributeError: # pragma: NO COVER
45 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
46
47from google.api import distribution_pb2 # type: ignore
48from google.api import metric_pb2 # type: ignore
49from google.cloud.logging_v2.services.metrics_service_v2 import pagers
50from google.cloud.logging_v2.types import logging_metrics
51from google.longrunning import operations_pb2 # type: ignore
52from google.protobuf import timestamp_pb2 # type: ignore
53from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO
54from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport
55from .client import MetricsServiceV2Client
56
57try:
58 from google.api_core import client_logging # type: ignore
59
60 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
61except ImportError: # pragma: NO COVER
62 CLIENT_LOGGING_SUPPORTED = False
63
64_LOGGER = std_logging.getLogger(__name__)
65
66
67class MetricsServiceV2AsyncClient:
68 """Service for configuring logs-based metrics."""
69
70 _client: MetricsServiceV2Client
71
72 # Copy defaults from the synchronous client for use here.
73 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
74 DEFAULT_ENDPOINT = MetricsServiceV2Client.DEFAULT_ENDPOINT
75 DEFAULT_MTLS_ENDPOINT = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT
76 _DEFAULT_ENDPOINT_TEMPLATE = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE
77 _DEFAULT_UNIVERSE = MetricsServiceV2Client._DEFAULT_UNIVERSE
78
79 log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path)
80 parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path)
81 common_billing_account_path = staticmethod(
82 MetricsServiceV2Client.common_billing_account_path
83 )
84 parse_common_billing_account_path = staticmethod(
85 MetricsServiceV2Client.parse_common_billing_account_path
86 )
87 common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path)
88 parse_common_folder_path = staticmethod(
89 MetricsServiceV2Client.parse_common_folder_path
90 )
91 common_organization_path = staticmethod(
92 MetricsServiceV2Client.common_organization_path
93 )
94 parse_common_organization_path = staticmethod(
95 MetricsServiceV2Client.parse_common_organization_path
96 )
97 common_project_path = staticmethod(MetricsServiceV2Client.common_project_path)
98 parse_common_project_path = staticmethod(
99 MetricsServiceV2Client.parse_common_project_path
100 )
101 common_location_path = staticmethod(MetricsServiceV2Client.common_location_path)
102 parse_common_location_path = staticmethod(
103 MetricsServiceV2Client.parse_common_location_path
104 )
105
106 @classmethod
107 def from_service_account_info(cls, info: dict, *args, **kwargs):
108 """Creates an instance of this client using the provided credentials
109 info.
110
111 Args:
112 info (dict): The service account private key info.
113 args: Additional arguments to pass to the constructor.
114 kwargs: Additional arguments to pass to the constructor.
115
116 Returns:
117 MetricsServiceV2AsyncClient: The constructed client.
118 """
119 return MetricsServiceV2Client.from_service_account_info.__func__(MetricsServiceV2AsyncClient, info, *args, **kwargs) # type: ignore
120
121 @classmethod
122 def from_service_account_file(cls, filename: str, *args, **kwargs):
123 """Creates an instance of this client using the provided credentials
124 file.
125
126 Args:
127 filename (str): The path to the service account private key json
128 file.
129 args: Additional arguments to pass to the constructor.
130 kwargs: Additional arguments to pass to the constructor.
131
132 Returns:
133 MetricsServiceV2AsyncClient: The constructed client.
134 """
135 return MetricsServiceV2Client.from_service_account_file.__func__(MetricsServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore
136
137 from_service_account_json = from_service_account_file
138
139 @classmethod
140 def get_mtls_endpoint_and_cert_source(
141 cls, client_options: Optional[ClientOptions] = None
142 ):
143 """Return the API endpoint and client cert source for mutual TLS.
144
145 The client cert source is determined in the following order:
146 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
147 client cert source is None.
148 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
149 default client cert source exists, use the default one; otherwise the client cert
150 source is None.
151
152 The API endpoint is determined in the following order:
153 (1) if `client_options.api_endpoint` if provided, use the provided one.
154 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
155 default mTLS endpoint; if the environment variable is "never", use the default API
156 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
157 use the default API endpoint.
158
159 More details can be found at https://google.aip.dev/auth/4114.
160
161 Args:
162 client_options (google.api_core.client_options.ClientOptions): Custom options for the
163 client. Only the `api_endpoint` and `client_cert_source` properties may be used
164 in this method.
165
166 Returns:
167 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
168 client cert source to use.
169
170 Raises:
171 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
172 """
173 return MetricsServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
174
175 @property
176 def transport(self) -> MetricsServiceV2Transport:
177 """Returns the transport used by the client instance.
178
179 Returns:
180 MetricsServiceV2Transport: The transport used by the client instance.
181 """
182 return self._client.transport
183
184 @property
185 def api_endpoint(self):
186 """Return the API endpoint used by the client instance.
187
188 Returns:
189 str: The API endpoint used by the client instance.
190 """
191 return self._client._api_endpoint
192
193 @property
194 def universe_domain(self) -> str:
195 """Return the universe domain used by the client instance.
196
197 Returns:
198 str: The universe domain used
199 by the client instance.
200 """
201 return self._client._universe_domain
202
203 get_transport_class = MetricsServiceV2Client.get_transport_class
204
205 def __init__(
206 self,
207 *,
208 credentials: Optional[ga_credentials.Credentials] = None,
209 transport: Optional[
210 Union[
211 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport]
212 ]
213 ] = "grpc_asyncio",
214 client_options: Optional[ClientOptions] = None,
215 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
216 ) -> None:
217 """Instantiates the metrics service v2 async client.
218
219 Args:
220 credentials (Optional[google.auth.credentials.Credentials]): The
221 authorization credentials to attach to requests. These
222 credentials identify the application to the service; if none
223 are specified, the client will attempt to ascertain the
224 credentials from the environment.
225 transport (Optional[Union[str,MetricsServiceV2Transport,Callable[..., MetricsServiceV2Transport]]]):
226 The transport to use, or a Callable that constructs and returns a new transport to use.
227 If a Callable is given, it will be called with the same set of initialization
228 arguments as used in the MetricsServiceV2Transport constructor.
229 If set to None, a transport is chosen automatically.
230 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
231 Custom options for the client.
232
233 1. The ``api_endpoint`` property can be used to override the
234 default endpoint provided by the client when ``transport`` is
235 not explicitly provided. Only if this property is not set and
236 ``transport`` was not explicitly provided, the endpoint is
237 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
238 variable, which have one of the following values:
239 "always" (always use the default mTLS endpoint), "never" (always
240 use the default regular endpoint) and "auto" (auto-switch to the
241 default mTLS endpoint if client certificate is present; this is
242 the default value).
243
244 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
245 is "true", then the ``client_cert_source`` property can be used
246 to provide a client certificate for mTLS transport. If
247 not provided, the default SSL client certificate will be used if
248 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
249 set, no client certificate will be used.
250
251 3. The ``universe_domain`` property can be used to override the
252 default "googleapis.com" universe. Note that ``api_endpoint``
253 property still takes precedence; and ``universe_domain`` is
254 currently not supported for mTLS.
255
256 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
257 The client info used to send a user-agent string along with
258 API requests. If ``None``, then default info will be used.
259 Generally, you only need to set this if you're developing
260 your own client library.
261
262 Raises:
263 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
264 creation failed for any reason.
265 """
266 self._client = MetricsServiceV2Client(
267 credentials=credentials,
268 transport=transport,
269 client_options=client_options,
270 client_info=client_info,
271 )
272
273 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
274 std_logging.DEBUG
275 ): # pragma: NO COVER
276 _LOGGER.debug(
277 "Created client `google.logging_v2.MetricsServiceV2AsyncClient`.",
278 extra={
279 "serviceName": "google.logging.v2.MetricsServiceV2",
280 "universeDomain": getattr(
281 self._client._transport._credentials, "universe_domain", ""
282 ),
283 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
284 "credentialsInfo": getattr(
285 self.transport._credentials, "get_cred_info", lambda: None
286 )(),
287 }
288 if hasattr(self._client._transport, "_credentials")
289 else {
290 "serviceName": "google.logging.v2.MetricsServiceV2",
291 "credentialsType": None,
292 },
293 )
294
295 async def list_log_metrics(
296 self,
297 request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None,
298 *,
299 parent: Optional[str] = None,
300 retry: OptionalRetry = gapic_v1.method.DEFAULT,
301 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
302 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
303 ) -> pagers.ListLogMetricsAsyncPager:
304 r"""Lists logs-based metrics.
305
306 .. code-block:: python
307
308 # This snippet has been automatically generated and should be regarded as a
309 # code template only.
310 # It will require modifications to work:
311 # - It may require correct/in-range values for request initialization.
312 # - It may require specifying regional endpoints when creating the service
313 # client as shown in:
314 # https://googleapis.dev/python/google-api-core/latest/client_options.html
315 from google.cloud import logging_v2
316
317 async def sample_list_log_metrics():
318 # Create a client
319 client = logging_v2.MetricsServiceV2AsyncClient()
320
321 # Initialize request argument(s)
322 request = logging_v2.ListLogMetricsRequest(
323 parent="parent_value",
324 )
325
326 # Make the request
327 page_result = client.list_log_metrics(request=request)
328
329 # Handle the response
330 async for response in page_result:
331 print(response)
332
333 Args:
334 request (Optional[Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]]):
335 The request object. The parameters to ListLogMetrics.
336 parent (:class:`str`):
337 Required. The name of the project containing the
338 metrics:
339
340 ::
341
342 "projects/[PROJECT_ID]"
343
344 This corresponds to the ``parent`` field
345 on the ``request`` instance; if ``request`` is provided, this
346 should not be set.
347 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
348 should be retried.
349 timeout (float): The timeout for this request.
350 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
351 sent along with the request as metadata. Normally, each value must be of type `str`,
352 but for metadata keys ending with the suffix `-bin`, the corresponding values must
353 be of type `bytes`.
354
355 Returns:
356 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsAsyncPager:
357 Result returned from ListLogMetrics.
358
359 Iterating over this object will yield
360 results and resolve additional pages
361 automatically.
362
363 """
364 # Create or coerce a protobuf request object.
365 # - Quick check: If we got a request object, we should *not* have
366 # gotten any keyword arguments that map to the request.
367 flattened_params = [parent]
368 has_flattened_params = (
369 len([param for param in flattened_params if param is not None]) > 0
370 )
371 if request is not None and has_flattened_params:
372 raise ValueError(
373 "If the `request` argument is set, then none of "
374 "the individual field arguments should be set."
375 )
376
377 # - Use the request object if provided (there's no risk of modifying the input as
378 # there are no flattened fields), or create one.
379 if not isinstance(request, logging_metrics.ListLogMetricsRequest):
380 request = logging_metrics.ListLogMetricsRequest(request)
381
382 # If we have keyword arguments corresponding to fields on the
383 # request, apply these.
384 if parent is not None:
385 request.parent = parent
386
387 # Wrap the RPC method; this adds retry and timeout information,
388 # and friendly error handling.
389 rpc = self._client._transport._wrapped_methods[
390 self._client._transport.list_log_metrics
391 ]
392
393 # Certain fields should be provided within the metadata header;
394 # add these here.
395 metadata = tuple(metadata) + (
396 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
397 )
398
399 # Validate the universe domain.
400 self._client._validate_universe_domain()
401
402 # Send the request.
403 response = await rpc(
404 request,
405 retry=retry,
406 timeout=timeout,
407 metadata=metadata,
408 )
409
410 # This method is paged; wrap the response in a pager, which provides
411 # an `__aiter__` convenience method.
412 response = pagers.ListLogMetricsAsyncPager(
413 method=rpc,
414 request=request,
415 response=response,
416 retry=retry,
417 timeout=timeout,
418 metadata=metadata,
419 )
420
421 # Done; return the response.
422 return response
423
424 async def get_log_metric(
425 self,
426 request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None,
427 *,
428 metric_name: Optional[str] = None,
429 retry: OptionalRetry = gapic_v1.method.DEFAULT,
430 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
431 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
432 ) -> logging_metrics.LogMetric:
433 r"""Gets a logs-based metric.
434
435 .. code-block:: python
436
437 # This snippet has been automatically generated and should be regarded as a
438 # code template only.
439 # It will require modifications to work:
440 # - It may require correct/in-range values for request initialization.
441 # - It may require specifying regional endpoints when creating the service
442 # client as shown in:
443 # https://googleapis.dev/python/google-api-core/latest/client_options.html
444 from google.cloud import logging_v2
445
446 async def sample_get_log_metric():
447 # Create a client
448 client = logging_v2.MetricsServiceV2AsyncClient()
449
450 # Initialize request argument(s)
451 request = logging_v2.GetLogMetricRequest(
452 metric_name="metric_name_value",
453 )
454
455 # Make the request
456 response = await client.get_log_metric(request=request)
457
458 # Handle the response
459 print(response)
460
461 Args:
462 request (Optional[Union[google.cloud.logging_v2.types.GetLogMetricRequest, dict]]):
463 The request object. The parameters to GetLogMetric.
464 metric_name (:class:`str`):
465 Required. The resource name of the desired metric:
466
467 ::
468
469 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
470
471 This corresponds to the ``metric_name`` field
472 on the ``request`` instance; if ``request`` is provided, this
473 should not be set.
474 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
475 should be retried.
476 timeout (float): The timeout for this request.
477 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
478 sent along with the request as metadata. Normally, each value must be of type `str`,
479 but for metadata keys ending with the suffix `-bin`, the corresponding values must
480 be of type `bytes`.
481
482 Returns:
483 google.cloud.logging_v2.types.LogMetric:
484 Describes a logs-based metric. The
485 value of the metric is the number of log
486 entries that match a logs filter in a
487 given time interval.
488
489 Logs-based metrics can also be used to
490 extract values from logs and create a
491 distribution of the values. The
492 distribution records the statistics of
493 the extracted values along with an
494 optional histogram of the values as
495 specified by the bucket options.
496
497 """
498 # Create or coerce a protobuf request object.
499 # - Quick check: If we got a request object, we should *not* have
500 # gotten any keyword arguments that map to the request.
501 flattened_params = [metric_name]
502 has_flattened_params = (
503 len([param for param in flattened_params if param is not None]) > 0
504 )
505 if request is not None and has_flattened_params:
506 raise ValueError(
507 "If the `request` argument is set, then none of "
508 "the individual field arguments should be set."
509 )
510
511 # - Use the request object if provided (there's no risk of modifying the input as
512 # there are no flattened fields), or create one.
513 if not isinstance(request, logging_metrics.GetLogMetricRequest):
514 request = logging_metrics.GetLogMetricRequest(request)
515
516 # If we have keyword arguments corresponding to fields on the
517 # request, apply these.
518 if metric_name is not None:
519 request.metric_name = metric_name
520
521 # Wrap the RPC method; this adds retry and timeout information,
522 # and friendly error handling.
523 rpc = self._client._transport._wrapped_methods[
524 self._client._transport.get_log_metric
525 ]
526
527 # Certain fields should be provided within the metadata header;
528 # add these here.
529 metadata = tuple(metadata) + (
530 gapic_v1.routing_header.to_grpc_metadata(
531 (("metric_name", request.metric_name),)
532 ),
533 )
534
535 # Validate the universe domain.
536 self._client._validate_universe_domain()
537
538 # Send the request.
539 response = await rpc(
540 request,
541 retry=retry,
542 timeout=timeout,
543 metadata=metadata,
544 )
545
546 # Done; return the response.
547 return response
548
549 async def create_log_metric(
550 self,
551 request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None,
552 *,
553 parent: Optional[str] = None,
554 metric: Optional[logging_metrics.LogMetric] = None,
555 retry: OptionalRetry = gapic_v1.method.DEFAULT,
556 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
557 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
558 ) -> logging_metrics.LogMetric:
559 r"""Creates a logs-based metric.
560
561 .. code-block:: python
562
563 # This snippet has been automatically generated and should be regarded as a
564 # code template only.
565 # It will require modifications to work:
566 # - It may require correct/in-range values for request initialization.
567 # - It may require specifying regional endpoints when creating the service
568 # client as shown in:
569 # https://googleapis.dev/python/google-api-core/latest/client_options.html
570 from google.cloud import logging_v2
571
572 async def sample_create_log_metric():
573 # Create a client
574 client = logging_v2.MetricsServiceV2AsyncClient()
575
576 # Initialize request argument(s)
577 metric = logging_v2.LogMetric()
578 metric.name = "name_value"
579 metric.filter = "filter_value"
580
581 request = logging_v2.CreateLogMetricRequest(
582 parent="parent_value",
583 metric=metric,
584 )
585
586 # Make the request
587 response = await client.create_log_metric(request=request)
588
589 # Handle the response
590 print(response)
591
592 Args:
593 request (Optional[Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]]):
594 The request object. The parameters to CreateLogMetric.
595 parent (:class:`str`):
596 Required. The resource name of the project in which to
597 create the metric:
598
599 ::
600
601 "projects/[PROJECT_ID]"
602
603 The new metric must be provided in the request.
604
605 This corresponds to the ``parent`` field
606 on the ``request`` instance; if ``request`` is provided, this
607 should not be set.
608 metric (:class:`google.cloud.logging_v2.types.LogMetric`):
609 Required. The new logs-based metric,
610 which must not have an identifier that
611 already exists.
612
613 This corresponds to the ``metric`` field
614 on the ``request`` instance; if ``request`` is provided, this
615 should not be set.
616 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
617 should be retried.
618 timeout (float): The timeout for this request.
619 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
620 sent along with the request as metadata. Normally, each value must be of type `str`,
621 but for metadata keys ending with the suffix `-bin`, the corresponding values must
622 be of type `bytes`.
623
624 Returns:
625 google.cloud.logging_v2.types.LogMetric:
626 Describes a logs-based metric. The
627 value of the metric is the number of log
628 entries that match a logs filter in a
629 given time interval.
630
631 Logs-based metrics can also be used to
632 extract values from logs and create a
633 distribution of the values. The
634 distribution records the statistics of
635 the extracted values along with an
636 optional histogram of the values as
637 specified by the bucket options.
638
639 """
640 # Create or coerce a protobuf request object.
641 # - Quick check: If we got a request object, we should *not* have
642 # gotten any keyword arguments that map to the request.
643 flattened_params = [parent, metric]
644 has_flattened_params = (
645 len([param for param in flattened_params if param is not None]) > 0
646 )
647 if request is not None and has_flattened_params:
648 raise ValueError(
649 "If the `request` argument is set, then none of "
650 "the individual field arguments should be set."
651 )
652
653 # - Use the request object if provided (there's no risk of modifying the input as
654 # there are no flattened fields), or create one.
655 if not isinstance(request, logging_metrics.CreateLogMetricRequest):
656 request = logging_metrics.CreateLogMetricRequest(request)
657
658 # If we have keyword arguments corresponding to fields on the
659 # request, apply these.
660 if parent is not None:
661 request.parent = parent
662 if metric is not None:
663 request.metric = metric
664
665 # Wrap the RPC method; this adds retry and timeout information,
666 # and friendly error handling.
667 rpc = self._client._transport._wrapped_methods[
668 self._client._transport.create_log_metric
669 ]
670
671 # Certain fields should be provided within the metadata header;
672 # add these here.
673 metadata = tuple(metadata) + (
674 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
675 )
676
677 # Validate the universe domain.
678 self._client._validate_universe_domain()
679
680 # Send the request.
681 response = await rpc(
682 request,
683 retry=retry,
684 timeout=timeout,
685 metadata=metadata,
686 )
687
688 # Done; return the response.
689 return response
690
691 async def update_log_metric(
692 self,
693 request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None,
694 *,
695 metric_name: Optional[str] = None,
696 metric: Optional[logging_metrics.LogMetric] = None,
697 retry: OptionalRetry = gapic_v1.method.DEFAULT,
698 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
699 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
700 ) -> logging_metrics.LogMetric:
701 r"""Creates or updates a logs-based metric.
702
703 .. code-block:: python
704
705 # This snippet has been automatically generated and should be regarded as a
706 # code template only.
707 # It will require modifications to work:
708 # - It may require correct/in-range values for request initialization.
709 # - It may require specifying regional endpoints when creating the service
710 # client as shown in:
711 # https://googleapis.dev/python/google-api-core/latest/client_options.html
712 from google.cloud import logging_v2
713
714 async def sample_update_log_metric():
715 # Create a client
716 client = logging_v2.MetricsServiceV2AsyncClient()
717
718 # Initialize request argument(s)
719 metric = logging_v2.LogMetric()
720 metric.name = "name_value"
721 metric.filter = "filter_value"
722
723 request = logging_v2.UpdateLogMetricRequest(
724 metric_name="metric_name_value",
725 metric=metric,
726 )
727
728 # Make the request
729 response = await client.update_log_metric(request=request)
730
731 # Handle the response
732 print(response)
733
734 Args:
735 request (Optional[Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]]):
736 The request object. The parameters to UpdateLogMetric.
737 metric_name (:class:`str`):
738 Required. The resource name of the metric to update:
739
740 ::
741
742 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
743
744 The updated metric must be provided in the request and
745 it's ``name`` field must be the same as ``[METRIC_ID]``
746 If the metric does not exist in ``[PROJECT_ID]``, then a
747 new metric is created.
748
749 This corresponds to the ``metric_name`` field
750 on the ``request`` instance; if ``request`` is provided, this
751 should not be set.
752 metric (:class:`google.cloud.logging_v2.types.LogMetric`):
753 Required. The updated metric.
754 This corresponds to the ``metric`` field
755 on the ``request`` instance; if ``request`` is provided, this
756 should not be set.
757 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
758 should be retried.
759 timeout (float): The timeout for this request.
760 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
761 sent along with the request as metadata. Normally, each value must be of type `str`,
762 but for metadata keys ending with the suffix `-bin`, the corresponding values must
763 be of type `bytes`.
764
765 Returns:
766 google.cloud.logging_v2.types.LogMetric:
767 Describes a logs-based metric. The
768 value of the metric is the number of log
769 entries that match a logs filter in a
770 given time interval.
771
772 Logs-based metrics can also be used to
773 extract values from logs and create a
774 distribution of the values. The
775 distribution records the statistics of
776 the extracted values along with an
777 optional histogram of the values as
778 specified by the bucket options.
779
780 """
781 # Create or coerce a protobuf request object.
782 # - Quick check: If we got a request object, we should *not* have
783 # gotten any keyword arguments that map to the request.
784 flattened_params = [metric_name, metric]
785 has_flattened_params = (
786 len([param for param in flattened_params if param is not None]) > 0
787 )
788 if request is not None and has_flattened_params:
789 raise ValueError(
790 "If the `request` argument is set, then none of "
791 "the individual field arguments should be set."
792 )
793
794 # - Use the request object if provided (there's no risk of modifying the input as
795 # there are no flattened fields), or create one.
796 if not isinstance(request, logging_metrics.UpdateLogMetricRequest):
797 request = logging_metrics.UpdateLogMetricRequest(request)
798
799 # If we have keyword arguments corresponding to fields on the
800 # request, apply these.
801 if metric_name is not None:
802 request.metric_name = metric_name
803 if metric is not None:
804 request.metric = metric
805
806 # Wrap the RPC method; this adds retry and timeout information,
807 # and friendly error handling.
808 rpc = self._client._transport._wrapped_methods[
809 self._client._transport.update_log_metric
810 ]
811
812 # Certain fields should be provided within the metadata header;
813 # add these here.
814 metadata = tuple(metadata) + (
815 gapic_v1.routing_header.to_grpc_metadata(
816 (("metric_name", request.metric_name),)
817 ),
818 )
819
820 # Validate the universe domain.
821 self._client._validate_universe_domain()
822
823 # Send the request.
824 response = await rpc(
825 request,
826 retry=retry,
827 timeout=timeout,
828 metadata=metadata,
829 )
830
831 # Done; return the response.
832 return response
833
834 async def delete_log_metric(
835 self,
836 request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None,
837 *,
838 metric_name: Optional[str] = None,
839 retry: OptionalRetry = gapic_v1.method.DEFAULT,
840 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
841 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
842 ) -> None:
843 r"""Deletes a logs-based metric.
844
845 .. code-block:: python
846
847 # This snippet has been automatically generated and should be regarded as a
848 # code template only.
849 # It will require modifications to work:
850 # - It may require correct/in-range values for request initialization.
851 # - It may require specifying regional endpoints when creating the service
852 # client as shown in:
853 # https://googleapis.dev/python/google-api-core/latest/client_options.html
854 from google.cloud import logging_v2
855
856 async def sample_delete_log_metric():
857 # Create a client
858 client = logging_v2.MetricsServiceV2AsyncClient()
859
860 # Initialize request argument(s)
861 request = logging_v2.DeleteLogMetricRequest(
862 metric_name="metric_name_value",
863 )
864
865 # Make the request
866 await client.delete_log_metric(request=request)
867
868 Args:
869 request (Optional[Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]]):
870 The request object. The parameters to DeleteLogMetric.
871 metric_name (:class:`str`):
872 Required. The resource name of the metric to delete:
873
874 ::
875
876 "projects/[PROJECT_ID]/metrics/[METRIC_ID]"
877
878 This corresponds to the ``metric_name`` field
879 on the ``request`` instance; if ``request`` is provided, this
880 should not be set.
881 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
882 should be retried.
883 timeout (float): The timeout for this request.
884 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
885 sent along with the request as metadata. Normally, each value must be of type `str`,
886 but for metadata keys ending with the suffix `-bin`, the corresponding values must
887 be of type `bytes`.
888 """
889 # Create or coerce a protobuf request object.
890 # - Quick check: If we got a request object, we should *not* have
891 # gotten any keyword arguments that map to the request.
892 flattened_params = [metric_name]
893 has_flattened_params = (
894 len([param for param in flattened_params if param is not None]) > 0
895 )
896 if request is not None and has_flattened_params:
897 raise ValueError(
898 "If the `request` argument is set, then none of "
899 "the individual field arguments should be set."
900 )
901
902 # - Use the request object if provided (there's no risk of modifying the input as
903 # there are no flattened fields), or create one.
904 if not isinstance(request, logging_metrics.DeleteLogMetricRequest):
905 request = logging_metrics.DeleteLogMetricRequest(request)
906
907 # If we have keyword arguments corresponding to fields on the
908 # request, apply these.
909 if metric_name is not None:
910 request.metric_name = metric_name
911
912 # Wrap the RPC method; this adds retry and timeout information,
913 # and friendly error handling.
914 rpc = self._client._transport._wrapped_methods[
915 self._client._transport.delete_log_metric
916 ]
917
918 # Certain fields should be provided within the metadata header;
919 # add these here.
920 metadata = tuple(metadata) + (
921 gapic_v1.routing_header.to_grpc_metadata(
922 (("metric_name", request.metric_name),)
923 ),
924 )
925
926 # Validate the universe domain.
927 self._client._validate_universe_domain()
928
929 # Send the request.
930 await rpc(
931 request,
932 retry=retry,
933 timeout=timeout,
934 metadata=metadata,
935 )
936
937 async def list_operations(
938 self,
939 request: Optional[operations_pb2.ListOperationsRequest] = None,
940 *,
941 retry: OptionalRetry = gapic_v1.method.DEFAULT,
942 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
943 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
944 ) -> operations_pb2.ListOperationsResponse:
945 r"""Lists operations that match the specified filter in the request.
946
947 Args:
948 request (:class:`~.operations_pb2.ListOperationsRequest`):
949 The request object. Request message for
950 `ListOperations` method.
951 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
952 if any, should be retried.
953 timeout (float): The timeout for this request.
954 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
955 sent along with the request as metadata. Normally, each value must be of type `str`,
956 but for metadata keys ending with the suffix `-bin`, the corresponding values must
957 be of type `bytes`.
958 Returns:
959 ~.operations_pb2.ListOperationsResponse:
960 Response message for ``ListOperations`` method.
961 """
962 # Create or coerce a protobuf request object.
963 # The request isn't a proto-plus wrapped type,
964 # so it must be constructed via keyword expansion.
965 if isinstance(request, dict):
966 request = operations_pb2.ListOperationsRequest(**request)
967
968 # Wrap the RPC method; this adds retry and timeout information,
969 # and friendly error handling.
970 rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
971
972 # Certain fields should be provided within the metadata header;
973 # add these here.
974 metadata = tuple(metadata) + (
975 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
976 )
977
978 # Validate the universe domain.
979 self._client._validate_universe_domain()
980
981 # Send the request.
982 response = await rpc(
983 request,
984 retry=retry,
985 timeout=timeout,
986 metadata=metadata,
987 )
988
989 # Done; return the response.
990 return response
991
992 async def get_operation(
993 self,
994 request: Optional[operations_pb2.GetOperationRequest] = None,
995 *,
996 retry: OptionalRetry = gapic_v1.method.DEFAULT,
997 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
998 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
999 ) -> operations_pb2.Operation:
1000 r"""Gets the latest state of a long-running operation.
1001
1002 Args:
1003 request (:class:`~.operations_pb2.GetOperationRequest`):
1004 The request object. Request message for
1005 `GetOperation` method.
1006 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1007 if any, should be retried.
1008 timeout (float): The timeout for this request.
1009 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1010 sent along with the request as metadata. Normally, each value must be of type `str`,
1011 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1012 be of type `bytes`.
1013 Returns:
1014 ~.operations_pb2.Operation:
1015 An ``Operation`` object.
1016 """
1017 # Create or coerce a protobuf request object.
1018 # The request isn't a proto-plus wrapped type,
1019 # so it must be constructed via keyword expansion.
1020 if isinstance(request, dict):
1021 request = operations_pb2.GetOperationRequest(**request)
1022
1023 # Wrap the RPC method; this adds retry and timeout information,
1024 # and friendly error handling.
1025 rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
1026
1027 # Certain fields should be provided within the metadata header;
1028 # add these here.
1029 metadata = tuple(metadata) + (
1030 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1031 )
1032
1033 # Validate the universe domain.
1034 self._client._validate_universe_domain()
1035
1036 # Send the request.
1037 response = await rpc(
1038 request,
1039 retry=retry,
1040 timeout=timeout,
1041 metadata=metadata,
1042 )
1043
1044 # Done; return the response.
1045 return response
1046
1047 async def cancel_operation(
1048 self,
1049 request: Optional[operations_pb2.CancelOperationRequest] = None,
1050 *,
1051 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1052 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1053 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1054 ) -> None:
1055 r"""Starts asynchronous cancellation on a long-running operation.
1056
1057 The server makes a best effort to cancel the operation, but success
1058 is not guaranteed. If the server doesn't support this method, it returns
1059 `google.rpc.Code.UNIMPLEMENTED`.
1060
1061 Args:
1062 request (:class:`~.operations_pb2.CancelOperationRequest`):
1063 The request object. Request message for
1064 `CancelOperation` method.
1065 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1066 if any, should be retried.
1067 timeout (float): The timeout for this request.
1068 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1069 sent along with the request as metadata. Normally, each value must be of type `str`,
1070 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1071 be of type `bytes`.
1072 Returns:
1073 None
1074 """
1075 # Create or coerce a protobuf request object.
1076 # The request isn't a proto-plus wrapped type,
1077 # so it must be constructed via keyword expansion.
1078 if isinstance(request, dict):
1079 request = operations_pb2.CancelOperationRequest(**request)
1080
1081 # Wrap the RPC method; this adds retry and timeout information,
1082 # and friendly error handling.
1083 rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
1084
1085 # Certain fields should be provided within the metadata header;
1086 # add these here.
1087 metadata = tuple(metadata) + (
1088 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1089 )
1090
1091 # Validate the universe domain.
1092 self._client._validate_universe_domain()
1093
1094 # Send the request.
1095 await rpc(
1096 request,
1097 retry=retry,
1098 timeout=timeout,
1099 metadata=metadata,
1100 )
1101
1102 async def __aenter__(self) -> "MetricsServiceV2AsyncClient":
1103 return self
1104
1105 async def __aexit__(self, exc_type, exc, tb):
1106 await self.transport.close()
1107
1108
1109DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1110 gapic_version=package_version.__version__
1111)
1112
1113
1114__all__ = ("MetricsServiceV2AsyncClient",)