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