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 AsyncIterable,
27 Awaitable,
28 AsyncIterator,
29 Sequence,
30 Tuple,
31 Type,
32 Union,
33)
34import uuid
35
36from google.cloud.logging_v2 import gapic_version as package_version
37
38from google.api_core.client_options import ClientOptions
39from google.api_core import exceptions as core_exceptions
40from google.api_core import gapic_v1
41from google.api_core import retry_async as retries
42from google.auth import credentials as ga_credentials # type: ignore
43from google.oauth2 import service_account # type: ignore
44import google.protobuf
45
46
47try:
48 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
49except AttributeError: # pragma: NO COVER
50 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
51
52from google.api import monitored_resource_pb2 # type: ignore
53from google.cloud.logging_v2.services.logging_service_v2 import pagers
54from google.cloud.logging_v2.types import log_entry
55from google.cloud.logging_v2.types import logging
56from google.longrunning import operations_pb2 # type: ignore
57from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO
58from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport
59from .client import LoggingServiceV2Client
60
61try:
62 from google.api_core import client_logging # type: ignore
63
64 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
65except ImportError: # pragma: NO COVER
66 CLIENT_LOGGING_SUPPORTED = False
67
68_LOGGER = std_logging.getLogger(__name__)
69
70
71class LoggingServiceV2AsyncClient:
72 """Service for ingesting and querying logs."""
73
74 _client: LoggingServiceV2Client
75
76 # Copy defaults from the synchronous client for use here.
77 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
78 DEFAULT_ENDPOINT = LoggingServiceV2Client.DEFAULT_ENDPOINT
79 DEFAULT_MTLS_ENDPOINT = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT
80 _DEFAULT_ENDPOINT_TEMPLATE = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE
81 _DEFAULT_UNIVERSE = LoggingServiceV2Client._DEFAULT_UNIVERSE
82
83 log_path = staticmethod(LoggingServiceV2Client.log_path)
84 parse_log_path = staticmethod(LoggingServiceV2Client.parse_log_path)
85 common_billing_account_path = staticmethod(
86 LoggingServiceV2Client.common_billing_account_path
87 )
88 parse_common_billing_account_path = staticmethod(
89 LoggingServiceV2Client.parse_common_billing_account_path
90 )
91 common_folder_path = staticmethod(LoggingServiceV2Client.common_folder_path)
92 parse_common_folder_path = staticmethod(
93 LoggingServiceV2Client.parse_common_folder_path
94 )
95 common_organization_path = staticmethod(
96 LoggingServiceV2Client.common_organization_path
97 )
98 parse_common_organization_path = staticmethod(
99 LoggingServiceV2Client.parse_common_organization_path
100 )
101 common_project_path = staticmethod(LoggingServiceV2Client.common_project_path)
102 parse_common_project_path = staticmethod(
103 LoggingServiceV2Client.parse_common_project_path
104 )
105 common_location_path = staticmethod(LoggingServiceV2Client.common_location_path)
106 parse_common_location_path = staticmethod(
107 LoggingServiceV2Client.parse_common_location_path
108 )
109
110 @classmethod
111 def from_service_account_info(cls, info: dict, *args, **kwargs):
112 """Creates an instance of this client using the provided credentials
113 info.
114
115 Args:
116 info (dict): The service account private key info.
117 args: Additional arguments to pass to the constructor.
118 kwargs: Additional arguments to pass to the constructor.
119
120 Returns:
121 LoggingServiceV2AsyncClient: The constructed client.
122 """
123 return LoggingServiceV2Client.from_service_account_info.__func__(LoggingServiceV2AsyncClient, info, *args, **kwargs) # type: ignore
124
125 @classmethod
126 def from_service_account_file(cls, filename: str, *args, **kwargs):
127 """Creates an instance of this client using the provided credentials
128 file.
129
130 Args:
131 filename (str): The path to the service account private key json
132 file.
133 args: Additional arguments to pass to the constructor.
134 kwargs: Additional arguments to pass to the constructor.
135
136 Returns:
137 LoggingServiceV2AsyncClient: The constructed client.
138 """
139 return LoggingServiceV2Client.from_service_account_file.__func__(LoggingServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore
140
141 from_service_account_json = from_service_account_file
142
143 @classmethod
144 def get_mtls_endpoint_and_cert_source(
145 cls, client_options: Optional[ClientOptions] = None
146 ):
147 """Return the API endpoint and client cert source for mutual TLS.
148
149 The client cert source is determined in the following order:
150 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
151 client cert source is None.
152 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
153 default client cert source exists, use the default one; otherwise the client cert
154 source is None.
155
156 The API endpoint is determined in the following order:
157 (1) if `client_options.api_endpoint` if provided, use the provided one.
158 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
159 default mTLS endpoint; if the environment variable is "never", use the default API
160 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
161 use the default API endpoint.
162
163 More details can be found at https://google.aip.dev/auth/4114.
164
165 Args:
166 client_options (google.api_core.client_options.ClientOptions): Custom options for the
167 client. Only the `api_endpoint` and `client_cert_source` properties may be used
168 in this method.
169
170 Returns:
171 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
172 client cert source to use.
173
174 Raises:
175 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
176 """
177 return LoggingServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
178
179 @property
180 def transport(self) -> LoggingServiceV2Transport:
181 """Returns the transport used by the client instance.
182
183 Returns:
184 LoggingServiceV2Transport: The transport used by the client instance.
185 """
186 return self._client.transport
187
188 @property
189 def api_endpoint(self):
190 """Return the API endpoint used by the client instance.
191
192 Returns:
193 str: The API endpoint used by the client instance.
194 """
195 return self._client._api_endpoint
196
197 @property
198 def universe_domain(self) -> str:
199 """Return the universe domain used by the client instance.
200
201 Returns:
202 str: The universe domain used
203 by the client instance.
204 """
205 return self._client._universe_domain
206
207 get_transport_class = LoggingServiceV2Client.get_transport_class
208
209 def __init__(
210 self,
211 *,
212 credentials: Optional[ga_credentials.Credentials] = None,
213 transport: Optional[
214 Union[
215 str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]
216 ]
217 ] = "grpc_asyncio",
218 client_options: Optional[ClientOptions] = None,
219 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
220 ) -> None:
221 """Instantiates the logging service v2 async client.
222
223 Args:
224 credentials (Optional[google.auth.credentials.Credentials]): The
225 authorization credentials to attach to requests. These
226 credentials identify the application to the service; if none
227 are specified, the client will attempt to ascertain the
228 credentials from the environment.
229 transport (Optional[Union[str,LoggingServiceV2Transport,Callable[..., LoggingServiceV2Transport]]]):
230 The transport to use, or a Callable that constructs and returns a new transport to use.
231 If a Callable is given, it will be called with the same set of initialization
232 arguments as used in the LoggingServiceV2Transport constructor.
233 If set to None, a transport is chosen automatically.
234 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
235 Custom options for the client.
236
237 1. The ``api_endpoint`` property can be used to override the
238 default endpoint provided by the client when ``transport`` is
239 not explicitly provided. Only if this property is not set and
240 ``transport`` was not explicitly provided, the endpoint is
241 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
242 variable, which have one of the following values:
243 "always" (always use the default mTLS endpoint), "never" (always
244 use the default regular endpoint) and "auto" (auto-switch to the
245 default mTLS endpoint if client certificate is present; this is
246 the default value).
247
248 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
249 is "true", then the ``client_cert_source`` property can be used
250 to provide a client certificate for mTLS transport. If
251 not provided, the default SSL client certificate will be used if
252 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
253 set, no client certificate will be used.
254
255 3. The ``universe_domain`` property can be used to override the
256 default "googleapis.com" universe. Note that ``api_endpoint``
257 property still takes precedence; and ``universe_domain`` is
258 currently not supported for mTLS.
259
260 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
261 The client info used to send a user-agent string along with
262 API requests. If ``None``, then default info will be used.
263 Generally, you only need to set this if you're developing
264 your own client library.
265
266 Raises:
267 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
268 creation failed for any reason.
269 """
270 self._client = LoggingServiceV2Client(
271 credentials=credentials,
272 transport=transport,
273 client_options=client_options,
274 client_info=client_info,
275 )
276
277 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
278 std_logging.DEBUG
279 ): # pragma: NO COVER
280 _LOGGER.debug(
281 "Created client `google.logging_v2.LoggingServiceV2AsyncClient`.",
282 extra={
283 "serviceName": "google.logging.v2.LoggingServiceV2",
284 "universeDomain": getattr(
285 self._client._transport._credentials, "universe_domain", ""
286 ),
287 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
288 "credentialsInfo": getattr(
289 self.transport._credentials, "get_cred_info", lambda: None
290 )(),
291 }
292 if hasattr(self._client._transport, "_credentials")
293 else {
294 "serviceName": "google.logging.v2.LoggingServiceV2",
295 "credentialsType": None,
296 },
297 )
298
299 async def delete_log(
300 self,
301 request: Optional[Union[logging.DeleteLogRequest, dict]] = None,
302 *,
303 log_name: Optional[str] = None,
304 retry: OptionalRetry = gapic_v1.method.DEFAULT,
305 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
306 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
307 ) -> None:
308 r"""Deletes all the log entries in a log for the \_Default Log
309 Bucket. The log reappears if it receives new entries. Log
310 entries written shortly before the delete operation might not be
311 deleted. Entries received after the delete operation with a
312 timestamp before the operation will be deleted.
313
314 .. code-block:: python
315
316 # This snippet has been automatically generated and should be regarded as a
317 # code template only.
318 # It will require modifications to work:
319 # - It may require correct/in-range values for request initialization.
320 # - It may require specifying regional endpoints when creating the service
321 # client as shown in:
322 # https://googleapis.dev/python/google-api-core/latest/client_options.html
323 from google.cloud import logging_v2
324
325 async def sample_delete_log():
326 # Create a client
327 client = logging_v2.LoggingServiceV2AsyncClient()
328
329 # Initialize request argument(s)
330 request = logging_v2.DeleteLogRequest(
331 log_name="log_name_value",
332 )
333
334 # Make the request
335 await client.delete_log(request=request)
336
337 Args:
338 request (Optional[Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]]):
339 The request object. The parameters to DeleteLog.
340 log_name (:class:`str`):
341 Required. The resource name of the log to delete:
342
343 - ``projects/[PROJECT_ID]/logs/[LOG_ID]``
344 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]``
345 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]``
346 - ``folders/[FOLDER_ID]/logs/[LOG_ID]``
347
348 ``[LOG_ID]`` must be URL-encoded. For example,
349 ``"projects/my-project-id/logs/syslog"``,
350 ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``.
351
352 For more information about log names, see
353 [LogEntry][google.logging.v2.LogEntry].
354
355 This corresponds to the ``log_name`` field
356 on the ``request`` instance; if ``request`` is provided, this
357 should not be set.
358 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
359 should be retried.
360 timeout (float): The timeout for this request.
361 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
362 sent along with the request as metadata. Normally, each value must be of type `str`,
363 but for metadata keys ending with the suffix `-bin`, the corresponding values must
364 be of type `bytes`.
365 """
366 # Create or coerce a protobuf request object.
367 # - Quick check: If we got a request object, we should *not* have
368 # gotten any keyword arguments that map to the request.
369 flattened_params = [log_name]
370 has_flattened_params = (
371 len([param for param in flattened_params if param is not None]) > 0
372 )
373 if request is not None and has_flattened_params:
374 raise ValueError(
375 "If the `request` argument is set, then none of "
376 "the individual field arguments should be set."
377 )
378
379 # - Use the request object if provided (there's no risk of modifying the input as
380 # there are no flattened fields), or create one.
381 if not isinstance(request, logging.DeleteLogRequest):
382 request = logging.DeleteLogRequest(request)
383
384 # If we have keyword arguments corresponding to fields on the
385 # request, apply these.
386 if log_name is not None:
387 request.log_name = log_name
388
389 # Wrap the RPC method; this adds retry and timeout information,
390 # and friendly error handling.
391 rpc = self._client._transport._wrapped_methods[
392 self._client._transport.delete_log
393 ]
394
395 # Certain fields should be provided within the metadata header;
396 # add these here.
397 metadata = tuple(metadata) + (
398 gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)),
399 )
400
401 # Validate the universe domain.
402 self._client._validate_universe_domain()
403
404 # Send the request.
405 await rpc(
406 request,
407 retry=retry,
408 timeout=timeout,
409 metadata=metadata,
410 )
411
412 async def write_log_entries(
413 self,
414 request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None,
415 *,
416 log_name: Optional[str] = None,
417 resource: Optional[monitored_resource_pb2.MonitoredResource] = None,
418 labels: Optional[MutableMapping[str, str]] = None,
419 entries: Optional[MutableSequence[log_entry.LogEntry]] = None,
420 retry: OptionalRetry = gapic_v1.method.DEFAULT,
421 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
422 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
423 ) -> logging.WriteLogEntriesResponse:
424 r"""Writes log entries to Logging. This API method is the
425 only way to send log entries to Logging. This method is
426 used, directly or indirectly, by the Logging agent
427 (fluentd) and all logging libraries configured to use
428 Logging. A single request may contain log entries for a
429 maximum of 1000 different resources (projects,
430 organizations, billing accounts or folders)
431
432 .. code-block:: python
433
434 # This snippet has been automatically generated and should be regarded as a
435 # code template only.
436 # It will require modifications to work:
437 # - It may require correct/in-range values for request initialization.
438 # - It may require specifying regional endpoints when creating the service
439 # client as shown in:
440 # https://googleapis.dev/python/google-api-core/latest/client_options.html
441 from google.cloud import logging_v2
442
443 async def sample_write_log_entries():
444 # Create a client
445 client = logging_v2.LoggingServiceV2AsyncClient()
446
447 # Initialize request argument(s)
448 entries = logging_v2.LogEntry()
449 entries.log_name = "log_name_value"
450
451 request = logging_v2.WriteLogEntriesRequest(
452 entries=entries,
453 )
454
455 # Make the request
456 response = await client.write_log_entries(request=request)
457
458 # Handle the response
459 print(response)
460
461 Args:
462 request (Optional[Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]]):
463 The request object. The parameters to WriteLogEntries.
464 log_name (:class:`str`):
465 Optional. A default log resource name that is assigned
466 to all log entries in ``entries`` that do not specify a
467 value for ``log_name``:
468
469 - ``projects/[PROJECT_ID]/logs/[LOG_ID]``
470 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]``
471 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]``
472 - ``folders/[FOLDER_ID]/logs/[LOG_ID]``
473
474 ``[LOG_ID]`` must be URL-encoded. For example:
475
476 ::
477
478 "projects/my-project-id/logs/syslog"
479 "organizations/123/logs/cloudaudit.googleapis.com%2Factivity"
480
481 The permission ``logging.logEntries.create`` is needed
482 on each project, organization, billing account, or
483 folder that is receiving new log entries, whether the
484 resource is specified in ``logName`` or in an individual
485 log entry.
486
487 This corresponds to the ``log_name`` field
488 on the ``request`` instance; if ``request`` is provided, this
489 should not be set.
490 resource (:class:`google.api.monitored_resource_pb2.MonitoredResource`):
491 Optional. A default monitored resource object that is
492 assigned to all log entries in ``entries`` that do not
493 specify a value for ``resource``. Example:
494
495 ::
496
497 { "type": "gce_instance",
498 "labels": {
499 "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
500
501 See [LogEntry][google.logging.v2.LogEntry].
502
503 This corresponds to the ``resource`` field
504 on the ``request`` instance; if ``request`` is provided, this
505 should not be set.
506 labels (:class:`MutableMapping[str, str]`):
507 Optional. Default labels that are added to the
508 ``labels`` field of all log entries in ``entries``. If a
509 log entry already has a label with the same key as a
510 label in this parameter, then the log entry's label is
511 not changed. See [LogEntry][google.logging.v2.LogEntry].
512
513 This corresponds to the ``labels`` field
514 on the ``request`` instance; if ``request`` is provided, this
515 should not be set.
516 entries (:class:`MutableSequence[google.cloud.logging_v2.types.LogEntry]`):
517 Required. The log entries to send to Logging. The order
518 of log entries in this list does not matter. Values
519 supplied in this method's ``log_name``, ``resource``,
520 and ``labels`` fields are copied into those log entries
521 in this list that do not include values for their
522 corresponding fields. For more information, see the
523 [LogEntry][google.logging.v2.LogEntry] type.
524
525 If the ``timestamp`` or ``insert_id`` fields are missing
526 in log entries, then this method supplies the current
527 time or a unique identifier, respectively. The supplied
528 values are chosen so that, among the log entries that
529 did not supply their own values, the entries earlier in
530 the list will sort before the entries later in the list.
531 See the ``entries.list`` method.
532
533 Log entries with timestamps that are more than the `logs
534 retention
535 period <https://cloud.google.com/logging/quotas>`__ in
536 the past or more than 24 hours in the future will not be
537 available when calling ``entries.list``. However, those
538 log entries can still be `exported with
539 LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__.
540
541 To improve throughput and to avoid exceeding the `quota
542 limit <https://cloud.google.com/logging/quotas>`__ for
543 calls to ``entries.write``, you should try to include
544 several log entries in this list, rather than calling
545 this method for each individual log entry.
546
547 This corresponds to the ``entries`` field
548 on the ``request`` instance; if ``request`` is provided, this
549 should not be set.
550 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
551 should be retried.
552 timeout (float): The timeout for this request.
553 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
554 sent along with the request as metadata. Normally, each value must be of type `str`,
555 but for metadata keys ending with the suffix `-bin`, the corresponding values must
556 be of type `bytes`.
557
558 Returns:
559 google.cloud.logging_v2.types.WriteLogEntriesResponse:
560 Result returned from WriteLogEntries.
561 """
562 # Create or coerce a protobuf request object.
563 # - Quick check: If we got a request object, we should *not* have
564 # gotten any keyword arguments that map to the request.
565 flattened_params = [log_name, resource, labels, entries]
566 has_flattened_params = (
567 len([param for param in flattened_params if param is not None]) > 0
568 )
569 if request is not None and has_flattened_params:
570 raise ValueError(
571 "If the `request` argument is set, then none of "
572 "the individual field arguments should be set."
573 )
574
575 # - Use the request object if provided (there's no risk of modifying the input as
576 # there are no flattened fields), or create one.
577 if not isinstance(request, logging.WriteLogEntriesRequest):
578 request = logging.WriteLogEntriesRequest(request)
579
580 # If we have keyword arguments corresponding to fields on the
581 # request, apply these.
582 if log_name is not None:
583 request.log_name = log_name
584 if resource is not None:
585 request.resource = resource
586
587 if labels:
588 request.labels.update(labels)
589 if entries:
590 request.entries.extend(entries)
591
592 # Wrap the RPC method; this adds retry and timeout information,
593 # and friendly error handling.
594 rpc = self._client._transport._wrapped_methods[
595 self._client._transport.write_log_entries
596 ]
597
598 # Validate the universe domain.
599 self._client._validate_universe_domain()
600
601 # Send the request.
602 response = await rpc(
603 request,
604 retry=retry,
605 timeout=timeout,
606 metadata=metadata,
607 )
608
609 # Done; return the response.
610 return response
611
612 async def list_log_entries(
613 self,
614 request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None,
615 *,
616 resource_names: Optional[MutableSequence[str]] = None,
617 filter: Optional[str] = None,
618 order_by: Optional[str] = None,
619 retry: OptionalRetry = gapic_v1.method.DEFAULT,
620 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
621 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
622 ) -> pagers.ListLogEntriesAsyncPager:
623 r"""Lists log entries. Use this method to retrieve log entries that
624 originated from a project/folder/organization/billing account.
625 For ways to export log entries, see `Exporting
626 Logs <https://cloud.google.com/logging/docs/export>`__.
627
628 .. code-block:: python
629
630 # This snippet has been automatically generated and should be regarded as a
631 # code template only.
632 # It will require modifications to work:
633 # - It may require correct/in-range values for request initialization.
634 # - It may require specifying regional endpoints when creating the service
635 # client as shown in:
636 # https://googleapis.dev/python/google-api-core/latest/client_options.html
637 from google.cloud import logging_v2
638
639 async def sample_list_log_entries():
640 # Create a client
641 client = logging_v2.LoggingServiceV2AsyncClient()
642
643 # Initialize request argument(s)
644 request = logging_v2.ListLogEntriesRequest(
645 resource_names=['resource_names_value1', 'resource_names_value2'],
646 )
647
648 # Make the request
649 page_result = client.list_log_entries(request=request)
650
651 # Handle the response
652 async for response in page_result:
653 print(response)
654
655 Args:
656 request (Optional[Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]]):
657 The request object. The parameters to ``ListLogEntries``.
658 resource_names (:class:`MutableSequence[str]`):
659 Required. Names of one or more parent resources from
660 which to retrieve log entries:
661
662 - ``projects/[PROJECT_ID]``
663 - ``organizations/[ORGANIZATION_ID]``
664 - ``billingAccounts/[BILLING_ACCOUNT_ID]``
665 - ``folders/[FOLDER_ID]``
666
667 May alternatively be one or more views:
668
669 - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
670 - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
671 - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
672 - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
673
674 Projects listed in the ``project_ids`` field are added
675 to this list. A maximum of 100 resources may be
676 specified in a single request.
677
678 This corresponds to the ``resource_names`` field
679 on the ``request`` instance; if ``request`` is provided, this
680 should not be set.
681 filter (:class:`str`):
682 Optional. Only log entries that match the filter are
683 returned. An empty filter matches all log entries in the
684 resources listed in ``resource_names``. Referencing a
685 parent resource that is not listed in ``resource_names``
686 will cause the filter to return no results. The maximum
687 length of a filter is 20,000 characters.
688
689 This corresponds to the ``filter`` field
690 on the ``request`` instance; if ``request`` is provided, this
691 should not be set.
692 order_by (:class:`str`):
693 Optional. How the results should be sorted. Presently,
694 the only permitted values are ``"timestamp asc"``
695 (default) and ``"timestamp desc"``. The first option
696 returns entries in order of increasing values of
697 ``LogEntry.timestamp`` (oldest first), and the second
698 option returns entries in order of decreasing timestamps
699 (newest first). Entries with equal timestamps are
700 returned in order of their ``insert_id`` values.
701
702 This corresponds to the ``order_by`` field
703 on the ``request`` instance; if ``request`` is provided, this
704 should not be set.
705 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
706 should be retried.
707 timeout (float): The timeout for this request.
708 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
709 sent along with the request as metadata. Normally, each value must be of type `str`,
710 but for metadata keys ending with the suffix `-bin`, the corresponding values must
711 be of type `bytes`.
712
713 Returns:
714 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesAsyncPager:
715 Result returned from ListLogEntries.
716
717 Iterating over this object will yield results and
718 resolve additional pages automatically.
719
720 """
721 # Create or coerce a protobuf request object.
722 # - Quick check: If we got a request object, we should *not* have
723 # gotten any keyword arguments that map to the request.
724 flattened_params = [resource_names, filter, order_by]
725 has_flattened_params = (
726 len([param for param in flattened_params if param is not None]) > 0
727 )
728 if request is not None and has_flattened_params:
729 raise ValueError(
730 "If the `request` argument is set, then none of "
731 "the individual field arguments should be set."
732 )
733
734 # - Use the request object if provided (there's no risk of modifying the input as
735 # there are no flattened fields), or create one.
736 if not isinstance(request, logging.ListLogEntriesRequest):
737 request = logging.ListLogEntriesRequest(request)
738
739 # If we have keyword arguments corresponding to fields on the
740 # request, apply these.
741 if filter is not None:
742 request.filter = filter
743 if order_by is not None:
744 request.order_by = order_by
745 if resource_names:
746 request.resource_names.extend(resource_names)
747
748 # Wrap the RPC method; this adds retry and timeout information,
749 # and friendly error handling.
750 rpc = self._client._transport._wrapped_methods[
751 self._client._transport.list_log_entries
752 ]
753
754 # Validate the universe domain.
755 self._client._validate_universe_domain()
756
757 # Send the request.
758 response = await rpc(
759 request,
760 retry=retry,
761 timeout=timeout,
762 metadata=metadata,
763 )
764
765 # This method is paged; wrap the response in a pager, which provides
766 # an `__aiter__` convenience method.
767 response = pagers.ListLogEntriesAsyncPager(
768 method=rpc,
769 request=request,
770 response=response,
771 retry=retry,
772 timeout=timeout,
773 metadata=metadata,
774 )
775
776 # Done; return the response.
777 return response
778
779 async def list_monitored_resource_descriptors(
780 self,
781 request: Optional[
782 Union[logging.ListMonitoredResourceDescriptorsRequest, dict]
783 ] = None,
784 *,
785 retry: OptionalRetry = gapic_v1.method.DEFAULT,
786 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
787 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
788 ) -> pagers.ListMonitoredResourceDescriptorsAsyncPager:
789 r"""Lists the descriptors for monitored resource types
790 used by Logging.
791
792 .. code-block:: python
793
794 # This snippet has been automatically generated and should be regarded as a
795 # code template only.
796 # It will require modifications to work:
797 # - It may require correct/in-range values for request initialization.
798 # - It may require specifying regional endpoints when creating the service
799 # client as shown in:
800 # https://googleapis.dev/python/google-api-core/latest/client_options.html
801 from google.cloud import logging_v2
802
803 async def sample_list_monitored_resource_descriptors():
804 # Create a client
805 client = logging_v2.LoggingServiceV2AsyncClient()
806
807 # Initialize request argument(s)
808 request = logging_v2.ListMonitoredResourceDescriptorsRequest(
809 )
810
811 # Make the request
812 page_result = client.list_monitored_resource_descriptors(request=request)
813
814 # Handle the response
815 async for response in page_result:
816 print(response)
817
818 Args:
819 request (Optional[Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]]):
820 The request object. The parameters to
821 ListMonitoredResourceDescriptors
822 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
823 should be retried.
824 timeout (float): The timeout for this request.
825 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
826 sent along with the request as metadata. Normally, each value must be of type `str`,
827 but for metadata keys ending with the suffix `-bin`, the corresponding values must
828 be of type `bytes`.
829
830 Returns:
831 google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsAsyncPager:
832 Result returned from
833 ListMonitoredResourceDescriptors.
834 Iterating over this object will yield
835 results and resolve additional pages
836 automatically.
837
838 """
839 # Create or coerce a protobuf request object.
840 # - Use the request object if provided (there's no risk of modifying the input as
841 # there are no flattened fields), or create one.
842 if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest):
843 request = logging.ListMonitoredResourceDescriptorsRequest(request)
844
845 # Wrap the RPC method; this adds retry and timeout information,
846 # and friendly error handling.
847 rpc = self._client._transport._wrapped_methods[
848 self._client._transport.list_monitored_resource_descriptors
849 ]
850
851 # Validate the universe domain.
852 self._client._validate_universe_domain()
853
854 # Send the request.
855 response = await rpc(
856 request,
857 retry=retry,
858 timeout=timeout,
859 metadata=metadata,
860 )
861
862 # This method is paged; wrap the response in a pager, which provides
863 # an `__aiter__` convenience method.
864 response = pagers.ListMonitoredResourceDescriptorsAsyncPager(
865 method=rpc,
866 request=request,
867 response=response,
868 retry=retry,
869 timeout=timeout,
870 metadata=metadata,
871 )
872
873 # Done; return the response.
874 return response
875
876 async def list_logs(
877 self,
878 request: Optional[Union[logging.ListLogsRequest, dict]] = None,
879 *,
880 parent: Optional[str] = None,
881 retry: OptionalRetry = gapic_v1.method.DEFAULT,
882 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
883 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
884 ) -> pagers.ListLogsAsyncPager:
885 r"""Lists the logs in projects, organizations, folders,
886 or billing accounts. Only logs that have entries are
887 listed.
888
889 .. code-block:: python
890
891 # This snippet has been automatically generated and should be regarded as a
892 # code template only.
893 # It will require modifications to work:
894 # - It may require correct/in-range values for request initialization.
895 # - It may require specifying regional endpoints when creating the service
896 # client as shown in:
897 # https://googleapis.dev/python/google-api-core/latest/client_options.html
898 from google.cloud import logging_v2
899
900 async def sample_list_logs():
901 # Create a client
902 client = logging_v2.LoggingServiceV2AsyncClient()
903
904 # Initialize request argument(s)
905 request = logging_v2.ListLogsRequest(
906 parent="parent_value",
907 )
908
909 # Make the request
910 page_result = client.list_logs(request=request)
911
912 # Handle the response
913 async for response in page_result:
914 print(response)
915
916 Args:
917 request (Optional[Union[google.cloud.logging_v2.types.ListLogsRequest, dict]]):
918 The request object. The parameters to ListLogs.
919 parent (:class:`str`):
920 Required. The resource name to list logs for:
921
922 - ``projects/[PROJECT_ID]``
923 - ``organizations/[ORGANIZATION_ID]``
924 - ``billingAccounts/[BILLING_ACCOUNT_ID]``
925 - ``folders/[FOLDER_ID]``
926
927 This corresponds to the ``parent`` field
928 on the ``request`` instance; if ``request`` is provided, this
929 should not be set.
930 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
931 should be retried.
932 timeout (float): The timeout for this request.
933 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
934 sent along with the request as metadata. Normally, each value must be of type `str`,
935 but for metadata keys ending with the suffix `-bin`, the corresponding values must
936 be of type `bytes`.
937
938 Returns:
939 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsAsyncPager:
940 Result returned from ListLogs.
941
942 Iterating over this object will yield
943 results and resolve additional pages
944 automatically.
945
946 """
947 # Create or coerce a protobuf request object.
948 # - Quick check: If we got a request object, we should *not* have
949 # gotten any keyword arguments that map to the request.
950 flattened_params = [parent]
951 has_flattened_params = (
952 len([param for param in flattened_params if param is not None]) > 0
953 )
954 if request is not None and has_flattened_params:
955 raise ValueError(
956 "If the `request` argument is set, then none of "
957 "the individual field arguments should be set."
958 )
959
960 # - Use the request object if provided (there's no risk of modifying the input as
961 # there are no flattened fields), or create one.
962 if not isinstance(request, logging.ListLogsRequest):
963 request = logging.ListLogsRequest(request)
964
965 # If we have keyword arguments corresponding to fields on the
966 # request, apply these.
967 if parent is not None:
968 request.parent = parent
969
970 # Wrap the RPC method; this adds retry and timeout information,
971 # and friendly error handling.
972 rpc = self._client._transport._wrapped_methods[
973 self._client._transport.list_logs
974 ]
975
976 # Certain fields should be provided within the metadata header;
977 # add these here.
978 metadata = tuple(metadata) + (
979 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
980 )
981
982 # Validate the universe domain.
983 self._client._validate_universe_domain()
984
985 # Send the request.
986 response = await rpc(
987 request,
988 retry=retry,
989 timeout=timeout,
990 metadata=metadata,
991 )
992
993 # This method is paged; wrap the response in a pager, which provides
994 # an `__aiter__` convenience method.
995 response = pagers.ListLogsAsyncPager(
996 method=rpc,
997 request=request,
998 response=response,
999 retry=retry,
1000 timeout=timeout,
1001 metadata=metadata,
1002 )
1003
1004 # Done; return the response.
1005 return response
1006
1007 def tail_log_entries(
1008 self,
1009 requests: Optional[AsyncIterator[logging.TailLogEntriesRequest]] = None,
1010 *,
1011 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1012 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1013 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1014 ) -> Awaitable[AsyncIterable[logging.TailLogEntriesResponse]]:
1015 r"""Streaming read of log entries as they are ingested.
1016 Until the stream is terminated, it will continue reading
1017 logs.
1018
1019 .. code-block:: python
1020
1021 # This snippet has been automatically generated and should be regarded as a
1022 # code template only.
1023 # It will require modifications to work:
1024 # - It may require correct/in-range values for request initialization.
1025 # - It may require specifying regional endpoints when creating the service
1026 # client as shown in:
1027 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1028 from google.cloud import logging_v2
1029
1030 async def sample_tail_log_entries():
1031 # Create a client
1032 client = logging_v2.LoggingServiceV2AsyncClient()
1033
1034 # Initialize request argument(s)
1035 request = logging_v2.TailLogEntriesRequest(
1036 resource_names=['resource_names_value1', 'resource_names_value2'],
1037 )
1038
1039 # This method expects an iterator which contains
1040 # 'logging_v2.TailLogEntriesRequest' objects
1041 # Here we create a generator that yields a single `request` for
1042 # demonstrative purposes.
1043 requests = [request]
1044
1045 def request_generator():
1046 for request in requests:
1047 yield request
1048
1049 # Make the request
1050 stream = await client.tail_log_entries(requests=request_generator())
1051
1052 # Handle the response
1053 async for response in stream:
1054 print(response)
1055
1056 Args:
1057 requests (AsyncIterator[`google.cloud.logging_v2.types.TailLogEntriesRequest`]):
1058 The request object AsyncIterator. The parameters to ``TailLogEntries``.
1059 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1060 should be retried.
1061 timeout (float): The timeout for this request.
1062 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1063 sent along with the request as metadata. Normally, each value must be of type `str`,
1064 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1065 be of type `bytes`.
1066
1067 Returns:
1068 AsyncIterable[google.cloud.logging_v2.types.TailLogEntriesResponse]:
1069 Result returned from TailLogEntries.
1070 """
1071
1072 # Wrap the RPC method; this adds retry and timeout information,
1073 # and friendly error handling.
1074 rpc = self._client._transport._wrapped_methods[
1075 self._client._transport.tail_log_entries
1076 ]
1077
1078 # Validate the universe domain.
1079 self._client._validate_universe_domain()
1080
1081 # Send the request.
1082 response = rpc(
1083 requests,
1084 retry=retry,
1085 timeout=timeout,
1086 metadata=metadata,
1087 )
1088
1089 # Done; return the response.
1090 return response
1091
1092 async def list_operations(
1093 self,
1094 request: Optional[operations_pb2.ListOperationsRequest] = None,
1095 *,
1096 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1097 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1098 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1099 ) -> operations_pb2.ListOperationsResponse:
1100 r"""Lists operations that match the specified filter in the request.
1101
1102 Args:
1103 request (:class:`~.operations_pb2.ListOperationsRequest`):
1104 The request object. Request message for
1105 `ListOperations` method.
1106 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1107 if any, should be retried.
1108 timeout (float): The timeout for this request.
1109 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1110 sent along with the request as metadata. Normally, each value must be of type `str`,
1111 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1112 be of type `bytes`.
1113 Returns:
1114 ~.operations_pb2.ListOperationsResponse:
1115 Response message for ``ListOperations`` method.
1116 """
1117 # Create or coerce a protobuf request object.
1118 # The request isn't a proto-plus wrapped type,
1119 # so it must be constructed via keyword expansion.
1120 if isinstance(request, dict):
1121 request = operations_pb2.ListOperationsRequest(**request)
1122
1123 # Wrap the RPC method; this adds retry and timeout information,
1124 # and friendly error handling.
1125 rpc = self.transport._wrapped_methods[self._client._transport.list_operations]
1126
1127 # Certain fields should be provided within the metadata header;
1128 # add these here.
1129 metadata = tuple(metadata) + (
1130 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1131 )
1132
1133 # Validate the universe domain.
1134 self._client._validate_universe_domain()
1135
1136 # Send the request.
1137 response = await rpc(
1138 request,
1139 retry=retry,
1140 timeout=timeout,
1141 metadata=metadata,
1142 )
1143
1144 # Done; return the response.
1145 return response
1146
1147 async def get_operation(
1148 self,
1149 request: Optional[operations_pb2.GetOperationRequest] = None,
1150 *,
1151 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1152 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1153 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1154 ) -> operations_pb2.Operation:
1155 r"""Gets the latest state of a long-running operation.
1156
1157 Args:
1158 request (:class:`~.operations_pb2.GetOperationRequest`):
1159 The request object. Request message for
1160 `GetOperation` method.
1161 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1162 if any, should be retried.
1163 timeout (float): The timeout for this request.
1164 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1165 sent along with the request as metadata. Normally, each value must be of type `str`,
1166 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1167 be of type `bytes`.
1168 Returns:
1169 ~.operations_pb2.Operation:
1170 An ``Operation`` object.
1171 """
1172 # Create or coerce a protobuf request object.
1173 # The request isn't a proto-plus wrapped type,
1174 # so it must be constructed via keyword expansion.
1175 if isinstance(request, dict):
1176 request = operations_pb2.GetOperationRequest(**request)
1177
1178 # Wrap the RPC method; this adds retry and timeout information,
1179 # and friendly error handling.
1180 rpc = self.transport._wrapped_methods[self._client._transport.get_operation]
1181
1182 # Certain fields should be provided within the metadata header;
1183 # add these here.
1184 metadata = tuple(metadata) + (
1185 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1186 )
1187
1188 # Validate the universe domain.
1189 self._client._validate_universe_domain()
1190
1191 # Send the request.
1192 response = await rpc(
1193 request,
1194 retry=retry,
1195 timeout=timeout,
1196 metadata=metadata,
1197 )
1198
1199 # Done; return the response.
1200 return response
1201
1202 async def cancel_operation(
1203 self,
1204 request: Optional[operations_pb2.CancelOperationRequest] = None,
1205 *,
1206 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1207 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1208 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1209 ) -> None:
1210 r"""Starts asynchronous cancellation on a long-running operation.
1211
1212 The server makes a best effort to cancel the operation, but success
1213 is not guaranteed. If the server doesn't support this method, it returns
1214 `google.rpc.Code.UNIMPLEMENTED`.
1215
1216 Args:
1217 request (:class:`~.operations_pb2.CancelOperationRequest`):
1218 The request object. Request message for
1219 `CancelOperation` method.
1220 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1221 if any, should be retried.
1222 timeout (float): The timeout for this request.
1223 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1224 sent along with the request as metadata. Normally, each value must be of type `str`,
1225 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1226 be of type `bytes`.
1227 Returns:
1228 None
1229 """
1230 # Create or coerce a protobuf request object.
1231 # The request isn't a proto-plus wrapped type,
1232 # so it must be constructed via keyword expansion.
1233 if isinstance(request, dict):
1234 request = operations_pb2.CancelOperationRequest(**request)
1235
1236 # Wrap the RPC method; this adds retry and timeout information,
1237 # and friendly error handling.
1238 rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation]
1239
1240 # Certain fields should be provided within the metadata header;
1241 # add these here.
1242 metadata = tuple(metadata) + (
1243 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1244 )
1245
1246 # Validate the universe domain.
1247 self._client._validate_universe_domain()
1248
1249 # Send the request.
1250 await rpc(
1251 request,
1252 retry=retry,
1253 timeout=timeout,
1254 metadata=metadata,
1255 )
1256
1257 async def __aenter__(self) -> "LoggingServiceV2AsyncClient":
1258 return self
1259
1260 async def __aexit__(self, exc_type, exc, tb):
1261 await self.transport.close()
1262
1263
1264DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1265 gapic_version=package_version.__version__
1266)
1267
1268if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
1269 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
1270
1271
1272__all__ = ("LoggingServiceV2AsyncClient",)