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