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