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#
16from collections import OrderedDict
17from http import HTTPStatus
18import json
19import logging as std_logging
20import os
21import re
22from typing import (
23 Dict,
24 Callable,
25 Mapping,
26 MutableMapping,
27 MutableSequence,
28 Optional,
29 Iterable,
30 Iterator,
31 Sequence,
32 Tuple,
33 Type,
34 Union,
35 cast,
36)
37import uuid
38import warnings
39
40from google.cloud.logging_v2 import gapic_version as package_version
41
42from google.api_core import client_options as client_options_lib
43from google.api_core import exceptions as core_exceptions
44from google.api_core import gapic_v1
45from google.api_core import retry as retries
46from google.auth import credentials as ga_credentials # type: ignore
47from google.auth.transport import mtls # type: ignore
48from google.auth.transport.grpc import SslCredentials # type: ignore
49from google.auth.exceptions import MutualTLSChannelError # type: ignore
50from google.oauth2 import service_account # type: ignore
51import google.protobuf
52
53try:
54 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
55except AttributeError: # pragma: NO COVER
56 OptionalRetry = Union[retries.Retry, object, None] # type: ignore
57
58try:
59 from google.api_core import client_logging # type: ignore
60
61 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
62except ImportError: # pragma: NO COVER
63 CLIENT_LOGGING_SUPPORTED = False
64
65_LOGGER = std_logging.getLogger(__name__)
66
67from google.api import monitored_resource_pb2 # type: ignore
68from google.cloud.logging_v2.services.logging_service_v2 import pagers
69from google.cloud.logging_v2.types import log_entry
70from google.cloud.logging_v2.types import logging
71from google.longrunning import operations_pb2 # type: ignore
72from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO
73from .transports.grpc import LoggingServiceV2GrpcTransport
74from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport
75
76
77class LoggingServiceV2ClientMeta(type):
78 """Metaclass for the LoggingServiceV2 client.
79
80 This provides class-level methods for building and retrieving
81 support objects (e.g. transport) without polluting the client instance
82 objects.
83 """
84
85 _transport_registry = (
86 OrderedDict()
87 ) # type: Dict[str, Type[LoggingServiceV2Transport]]
88 _transport_registry["grpc"] = LoggingServiceV2GrpcTransport
89 _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport
90
91 def get_transport_class(
92 cls,
93 label: Optional[str] = None,
94 ) -> Type[LoggingServiceV2Transport]:
95 """Returns an appropriate transport class.
96
97 Args:
98 label: The name of the desired transport. If none is
99 provided, then the first transport in the registry is used.
100
101 Returns:
102 The transport class to use.
103 """
104 # If a specific transport is requested, return that one.
105 if label:
106 return cls._transport_registry[label]
107
108 # No transport is requested; return the default (that is, the first one
109 # in the dictionary).
110 return next(iter(cls._transport_registry.values()))
111
112
113class LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta):
114 """Service for ingesting and querying logs."""
115
116 @staticmethod
117 def _get_default_mtls_endpoint(api_endpoint):
118 """Converts api endpoint to mTLS endpoint.
119
120 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
121 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
122 Args:
123 api_endpoint (Optional[str]): the api endpoint to convert.
124 Returns:
125 str: converted mTLS api endpoint.
126 """
127 if not api_endpoint:
128 return api_endpoint
129
130 mtls_endpoint_re = re.compile(
131 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
132 )
133
134 m = mtls_endpoint_re.match(api_endpoint)
135 name, mtls, sandbox, googledomain = m.groups()
136 if mtls or not googledomain:
137 return api_endpoint
138
139 if sandbox:
140 return api_endpoint.replace(
141 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
142 )
143
144 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
145
146 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
147 DEFAULT_ENDPOINT = "logging.googleapis.com"
148 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
149 DEFAULT_ENDPOINT
150 )
151
152 _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}"
153 _DEFAULT_UNIVERSE = "googleapis.com"
154
155 @classmethod
156 def from_service_account_info(cls, info: dict, *args, **kwargs):
157 """Creates an instance of this client using the provided credentials
158 info.
159
160 Args:
161 info (dict): The service account private key info.
162 args: Additional arguments to pass to the constructor.
163 kwargs: Additional arguments to pass to the constructor.
164
165 Returns:
166 LoggingServiceV2Client: The constructed client.
167 """
168 credentials = service_account.Credentials.from_service_account_info(info)
169 kwargs["credentials"] = credentials
170 return cls(*args, **kwargs)
171
172 @classmethod
173 def from_service_account_file(cls, filename: str, *args, **kwargs):
174 """Creates an instance of this client using the provided credentials
175 file.
176
177 Args:
178 filename (str): The path to the service account private key json
179 file.
180 args: Additional arguments to pass to the constructor.
181 kwargs: Additional arguments to pass to the constructor.
182
183 Returns:
184 LoggingServiceV2Client: The constructed client.
185 """
186 credentials = service_account.Credentials.from_service_account_file(filename)
187 kwargs["credentials"] = credentials
188 return cls(*args, **kwargs)
189
190 from_service_account_json = from_service_account_file
191
192 @property
193 def transport(self) -> LoggingServiceV2Transport:
194 """Returns the transport used by the client instance.
195
196 Returns:
197 LoggingServiceV2Transport: The transport used by the client
198 instance.
199 """
200 return self._transport
201
202 @staticmethod
203 def log_path(
204 project: str,
205 log: str,
206 ) -> str:
207 """Returns a fully-qualified log string."""
208 return "projects/{project}/logs/{log}".format(
209 project=project,
210 log=log,
211 )
212
213 @staticmethod
214 def parse_log_path(path: str) -> Dict[str, str]:
215 """Parses a log path into its component segments."""
216 m = re.match(r"^projects/(?P<project>.+?)/logs/(?P<log>.+?)$", path)
217 return m.groupdict() if m else {}
218
219 @staticmethod
220 def common_billing_account_path(
221 billing_account: str,
222 ) -> str:
223 """Returns a fully-qualified billing_account string."""
224 return "billingAccounts/{billing_account}".format(
225 billing_account=billing_account,
226 )
227
228 @staticmethod
229 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
230 """Parse a billing_account path into its component segments."""
231 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
232 return m.groupdict() if m else {}
233
234 @staticmethod
235 def common_folder_path(
236 folder: str,
237 ) -> str:
238 """Returns a fully-qualified folder string."""
239 return "folders/{folder}".format(
240 folder=folder,
241 )
242
243 @staticmethod
244 def parse_common_folder_path(path: str) -> Dict[str, str]:
245 """Parse a folder path into its component segments."""
246 m = re.match(r"^folders/(?P<folder>.+?)$", path)
247 return m.groupdict() if m else {}
248
249 @staticmethod
250 def common_organization_path(
251 organization: str,
252 ) -> str:
253 """Returns a fully-qualified organization string."""
254 return "organizations/{organization}".format(
255 organization=organization,
256 )
257
258 @staticmethod
259 def parse_common_organization_path(path: str) -> Dict[str, str]:
260 """Parse a organization path into its component segments."""
261 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
262 return m.groupdict() if m else {}
263
264 @staticmethod
265 def common_project_path(
266 project: str,
267 ) -> str:
268 """Returns a fully-qualified project string."""
269 return "projects/{project}".format(
270 project=project,
271 )
272
273 @staticmethod
274 def parse_common_project_path(path: str) -> Dict[str, str]:
275 """Parse a project path into its component segments."""
276 m = re.match(r"^projects/(?P<project>.+?)$", path)
277 return m.groupdict() if m else {}
278
279 @staticmethod
280 def common_location_path(
281 project: str,
282 location: str,
283 ) -> str:
284 """Returns a fully-qualified location string."""
285 return "projects/{project}/locations/{location}".format(
286 project=project,
287 location=location,
288 )
289
290 @staticmethod
291 def parse_common_location_path(path: str) -> Dict[str, str]:
292 """Parse a location path into its component segments."""
293 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
294 return m.groupdict() if m else {}
295
296 @classmethod
297 def get_mtls_endpoint_and_cert_source(
298 cls, client_options: Optional[client_options_lib.ClientOptions] = None
299 ):
300 """Deprecated. Return the API endpoint and client cert source for mutual TLS.
301
302 The client cert source is determined in the following order:
303 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
304 client cert source is None.
305 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
306 default client cert source exists, use the default one; otherwise the client cert
307 source is None.
308
309 The API endpoint is determined in the following order:
310 (1) if `client_options.api_endpoint` if provided, use the provided one.
311 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
312 default mTLS endpoint; if the environment variable is "never", use the default API
313 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
314 use the default API endpoint.
315
316 More details can be found at https://google.aip.dev/auth/4114.
317
318 Args:
319 client_options (google.api_core.client_options.ClientOptions): Custom options for the
320 client. Only the `api_endpoint` and `client_cert_source` properties may be used
321 in this method.
322
323 Returns:
324 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
325 client cert source to use.
326
327 Raises:
328 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
329 """
330
331 warnings.warn(
332 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
333 DeprecationWarning,
334 )
335 if client_options is None:
336 client_options = client_options_lib.ClientOptions()
337 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
338 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
339 if use_client_cert not in ("true", "false"):
340 raise ValueError(
341 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
342 )
343 if use_mtls_endpoint not in ("auto", "never", "always"):
344 raise MutualTLSChannelError(
345 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
346 )
347
348 # Figure out the client cert source to use.
349 client_cert_source = None
350 if use_client_cert == "true":
351 if client_options.client_cert_source:
352 client_cert_source = client_options.client_cert_source
353 elif mtls.has_default_client_cert_source():
354 client_cert_source = mtls.default_client_cert_source()
355
356 # Figure out which api endpoint to use.
357 if client_options.api_endpoint is not None:
358 api_endpoint = client_options.api_endpoint
359 elif use_mtls_endpoint == "always" or (
360 use_mtls_endpoint == "auto" and client_cert_source
361 ):
362 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
363 else:
364 api_endpoint = cls.DEFAULT_ENDPOINT
365
366 return api_endpoint, client_cert_source
367
368 @staticmethod
369 def _read_environment_variables():
370 """Returns the environment variables used by the client.
371
372 Returns:
373 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
374 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
375
376 Raises:
377 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
378 any of ["true", "false"].
379 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
380 is not any of ["auto", "never", "always"].
381 """
382 use_client_cert = os.getenv(
383 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
384 ).lower()
385 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
386 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
387 if use_client_cert not in ("true", "false"):
388 raise ValueError(
389 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
390 )
391 if use_mtls_endpoint not in ("auto", "never", "always"):
392 raise MutualTLSChannelError(
393 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
394 )
395 return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
396
397 @staticmethod
398 def _get_client_cert_source(provided_cert_source, use_cert_flag):
399 """Return the client cert source to be used by the client.
400
401 Args:
402 provided_cert_source (bytes): The client certificate source provided.
403 use_cert_flag (bool): A flag indicating whether to use the client certificate.
404
405 Returns:
406 bytes or None: The client cert source to be used by the client.
407 """
408 client_cert_source = None
409 if use_cert_flag:
410 if provided_cert_source:
411 client_cert_source = provided_cert_source
412 elif mtls.has_default_client_cert_source():
413 client_cert_source = mtls.default_client_cert_source()
414 return client_cert_source
415
416 @staticmethod
417 def _get_api_endpoint(
418 api_override, client_cert_source, universe_domain, use_mtls_endpoint
419 ):
420 """Return the API endpoint used by the client.
421
422 Args:
423 api_override (str): The API endpoint override. If specified, this is always
424 the return value of this function and the other arguments are not used.
425 client_cert_source (bytes): The client certificate source used by the client.
426 universe_domain (str): The universe domain used by the client.
427 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
428 Possible values are "always", "auto", or "never".
429
430 Returns:
431 str: The API endpoint to be used by the client.
432 """
433 if api_override is not None:
434 api_endpoint = api_override
435 elif use_mtls_endpoint == "always" or (
436 use_mtls_endpoint == "auto" and client_cert_source
437 ):
438 _default_universe = LoggingServiceV2Client._DEFAULT_UNIVERSE
439 if universe_domain != _default_universe:
440 raise MutualTLSChannelError(
441 f"mTLS is not supported in any universe other than {_default_universe}."
442 )
443 api_endpoint = LoggingServiceV2Client.DEFAULT_MTLS_ENDPOINT
444 else:
445 api_endpoint = LoggingServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format(
446 UNIVERSE_DOMAIN=universe_domain
447 )
448 return api_endpoint
449
450 @staticmethod
451 def _get_universe_domain(
452 client_universe_domain: Optional[str], universe_domain_env: Optional[str]
453 ) -> str:
454 """Return the universe domain used by the client.
455
456 Args:
457 client_universe_domain (Optional[str]): The universe domain configured via the client options.
458 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
459
460 Returns:
461 str: The universe domain to be used by the client.
462
463 Raises:
464 ValueError: If the universe domain is an empty string.
465 """
466 universe_domain = LoggingServiceV2Client._DEFAULT_UNIVERSE
467 if client_universe_domain is not None:
468 universe_domain = client_universe_domain
469 elif universe_domain_env is not None:
470 universe_domain = universe_domain_env
471 if len(universe_domain.strip()) == 0:
472 raise ValueError("Universe Domain cannot be an empty string.")
473 return universe_domain
474
475 def _validate_universe_domain(self):
476 """Validates client's and credentials' universe domains are consistent.
477
478 Returns:
479 bool: True iff the configured universe domain is valid.
480
481 Raises:
482 ValueError: If the configured universe domain is not valid.
483 """
484
485 # NOTE (b/349488459): universe validation is disabled until further notice.
486 return True
487
488 def _add_cred_info_for_auth_errors(
489 self, error: core_exceptions.GoogleAPICallError
490 ) -> None:
491 """Adds credential info string to error details for 401/403/404 errors.
492
493 Args:
494 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info.
495 """
496 if error.code not in [
497 HTTPStatus.UNAUTHORIZED,
498 HTTPStatus.FORBIDDEN,
499 HTTPStatus.NOT_FOUND,
500 ]:
501 return
502
503 cred = self._transport._credentials
504
505 # get_cred_info is only available in google-auth>=2.35.0
506 if not hasattr(cred, "get_cred_info"):
507 return
508
509 # ignore the type check since pypy test fails when get_cred_info
510 # is not available
511 cred_info = cred.get_cred_info() # type: ignore
512 if cred_info and hasattr(error._details, "append"):
513 error._details.append(json.dumps(cred_info))
514
515 @property
516 def api_endpoint(self):
517 """Return the API endpoint used by the client instance.
518
519 Returns:
520 str: The API endpoint used by the client instance.
521 """
522 return self._api_endpoint
523
524 @property
525 def universe_domain(self) -> str:
526 """Return the universe domain used by the client instance.
527
528 Returns:
529 str: The universe domain used by the client instance.
530 """
531 return self._universe_domain
532
533 def __init__(
534 self,
535 *,
536 credentials: Optional[ga_credentials.Credentials] = None,
537 transport: Optional[
538 Union[
539 str, LoggingServiceV2Transport, Callable[..., LoggingServiceV2Transport]
540 ]
541 ] = None,
542 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
543 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
544 ) -> None:
545 """Instantiates the logging service v2 client.
546
547 Args:
548 credentials (Optional[google.auth.credentials.Credentials]): The
549 authorization credentials to attach to requests. These
550 credentials identify the application to the service; if none
551 are specified, the client will attempt to ascertain the
552 credentials from the environment.
553 transport (Optional[Union[str,LoggingServiceV2Transport,Callable[..., LoggingServiceV2Transport]]]):
554 The transport to use, or a Callable that constructs and returns a new transport.
555 If a Callable is given, it will be called with the same set of initialization
556 arguments as used in the LoggingServiceV2Transport constructor.
557 If set to None, a transport is chosen automatically.
558 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
559 Custom options for the client.
560
561 1. The ``api_endpoint`` property can be used to override the
562 default endpoint provided by the client when ``transport`` is
563 not explicitly provided. Only if this property is not set and
564 ``transport`` was not explicitly provided, the endpoint is
565 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
566 variable, which have one of the following values:
567 "always" (always use the default mTLS endpoint), "never" (always
568 use the default regular endpoint) and "auto" (auto-switch to the
569 default mTLS endpoint if client certificate is present; this is
570 the default value).
571
572 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
573 is "true", then the ``client_cert_source`` property can be used
574 to provide a client certificate for mTLS transport. If
575 not provided, the default SSL client certificate will be used if
576 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
577 set, no client certificate will be used.
578
579 3. The ``universe_domain`` property can be used to override the
580 default "googleapis.com" universe. Note that the ``api_endpoint``
581 property still takes precedence; and ``universe_domain`` is
582 currently not supported for mTLS.
583
584 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
585 The client info used to send a user-agent string along with
586 API requests. If ``None``, then default info will be used.
587 Generally, you only need to set this if you're developing
588 your own client library.
589
590 Raises:
591 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
592 creation failed for any reason.
593 """
594 self._client_options = client_options
595 if isinstance(self._client_options, dict):
596 self._client_options = client_options_lib.from_dict(self._client_options)
597 if self._client_options is None:
598 self._client_options = client_options_lib.ClientOptions()
599 self._client_options = cast(
600 client_options_lib.ClientOptions, self._client_options
601 )
602
603 universe_domain_opt = getattr(self._client_options, "universe_domain", None)
604
605 (
606 self._use_client_cert,
607 self._use_mtls_endpoint,
608 self._universe_domain_env,
609 ) = LoggingServiceV2Client._read_environment_variables()
610 self._client_cert_source = LoggingServiceV2Client._get_client_cert_source(
611 self._client_options.client_cert_source, self._use_client_cert
612 )
613 self._universe_domain = LoggingServiceV2Client._get_universe_domain(
614 universe_domain_opt, self._universe_domain_env
615 )
616 self._api_endpoint = None # updated below, depending on `transport`
617
618 # Initialize the universe domain validation.
619 self._is_universe_domain_valid = False
620
621 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
622 # Setup logging.
623 client_logging.initialize_logging()
624
625 api_key_value = getattr(self._client_options, "api_key", None)
626 if api_key_value and credentials:
627 raise ValueError(
628 "client_options.api_key and credentials are mutually exclusive"
629 )
630
631 # Save or instantiate the transport.
632 # Ordinarily, we provide the transport, but allowing a custom transport
633 # instance provides an extensibility point for unusual situations.
634 transport_provided = isinstance(transport, LoggingServiceV2Transport)
635 if transport_provided:
636 # transport is a LoggingServiceV2Transport instance.
637 if credentials or self._client_options.credentials_file or api_key_value:
638 raise ValueError(
639 "When providing a transport instance, "
640 "provide its credentials directly."
641 )
642 if self._client_options.scopes:
643 raise ValueError(
644 "When providing a transport instance, provide its scopes "
645 "directly."
646 )
647 self._transport = cast(LoggingServiceV2Transport, transport)
648 self._api_endpoint = self._transport.host
649
650 self._api_endpoint = (
651 self._api_endpoint
652 or LoggingServiceV2Client._get_api_endpoint(
653 self._client_options.api_endpoint,
654 self._client_cert_source,
655 self._universe_domain,
656 self._use_mtls_endpoint,
657 )
658 )
659
660 if not transport_provided:
661 import google.auth._default # type: ignore
662
663 if api_key_value and hasattr(
664 google.auth._default, "get_api_key_credentials"
665 ):
666 credentials = google.auth._default.get_api_key_credentials(
667 api_key_value
668 )
669
670 transport_init: Union[
671 Type[LoggingServiceV2Transport],
672 Callable[..., LoggingServiceV2Transport],
673 ] = (
674 LoggingServiceV2Client.get_transport_class(transport)
675 if isinstance(transport, str) or transport is None
676 else cast(Callable[..., LoggingServiceV2Transport], transport)
677 )
678 # initialize with the provided callable or the passed in class
679 self._transport = transport_init(
680 credentials=credentials,
681 credentials_file=self._client_options.credentials_file,
682 host=self._api_endpoint,
683 scopes=self._client_options.scopes,
684 client_cert_source_for_mtls=self._client_cert_source,
685 quota_project_id=self._client_options.quota_project_id,
686 client_info=client_info,
687 always_use_jwt_access=True,
688 api_audience=self._client_options.api_audience,
689 )
690
691 if "async" not in str(self._transport):
692 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
693 std_logging.DEBUG
694 ): # pragma: NO COVER
695 _LOGGER.debug(
696 "Created client `google.logging_v2.LoggingServiceV2Client`.",
697 extra={
698 "serviceName": "google.logging.v2.LoggingServiceV2",
699 "universeDomain": getattr(
700 self._transport._credentials, "universe_domain", ""
701 ),
702 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
703 "credentialsInfo": getattr(
704 self.transport._credentials, "get_cred_info", lambda: None
705 )(),
706 }
707 if hasattr(self._transport, "_credentials")
708 else {
709 "serviceName": "google.logging.v2.LoggingServiceV2",
710 "credentialsType": None,
711 },
712 )
713
714 def delete_log(
715 self,
716 request: Optional[Union[logging.DeleteLogRequest, dict]] = None,
717 *,
718 log_name: Optional[str] = None,
719 retry: OptionalRetry = gapic_v1.method.DEFAULT,
720 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
721 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
722 ) -> None:
723 r"""Deletes all the log entries in a log for the \_Default Log
724 Bucket. The log reappears if it receives new entries. Log
725 entries written shortly before the delete operation might not be
726 deleted. Entries received after the delete operation with a
727 timestamp before the operation will be deleted.
728
729 .. code-block:: python
730
731 # This snippet has been automatically generated and should be regarded as a
732 # code template only.
733 # It will require modifications to work:
734 # - It may require correct/in-range values for request initialization.
735 # - It may require specifying regional endpoints when creating the service
736 # client as shown in:
737 # https://googleapis.dev/python/google-api-core/latest/client_options.html
738 from google.cloud import logging_v2
739
740 def sample_delete_log():
741 # Create a client
742 client = logging_v2.LoggingServiceV2Client()
743
744 # Initialize request argument(s)
745 request = logging_v2.DeleteLogRequest(
746 log_name="log_name_value",
747 )
748
749 # Make the request
750 client.delete_log(request=request)
751
752 Args:
753 request (Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]):
754 The request object. The parameters to DeleteLog.
755 log_name (str):
756 Required. The resource name of the log to delete:
757
758 - ``projects/[PROJECT_ID]/logs/[LOG_ID]``
759 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]``
760 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]``
761 - ``folders/[FOLDER_ID]/logs/[LOG_ID]``
762
763 ``[LOG_ID]`` must be URL-encoded. For example,
764 ``"projects/my-project-id/logs/syslog"``,
765 ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``.
766
767 For more information about log names, see
768 [LogEntry][google.logging.v2.LogEntry].
769
770 This corresponds to the ``log_name`` field
771 on the ``request`` instance; if ``request`` is provided, this
772 should not be set.
773 retry (google.api_core.retry.Retry): Designation of what errors, if any,
774 should be retried.
775 timeout (float): The timeout for this request.
776 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
777 sent along with the request as metadata. Normally, each value must be of type `str`,
778 but for metadata keys ending with the suffix `-bin`, the corresponding values must
779 be of type `bytes`.
780 """
781 # Create or coerce a protobuf request object.
782 # - Quick check: If we got a request object, we should *not* have
783 # gotten any keyword arguments that map to the request.
784 flattened_params = [log_name]
785 has_flattened_params = (
786 len([param for param in flattened_params if param is not None]) > 0
787 )
788 if request is not None and has_flattened_params:
789 raise ValueError(
790 "If the `request` argument is set, then none of "
791 "the individual field arguments should be set."
792 )
793
794 # - Use the request object if provided (there's no risk of modifying the input as
795 # there are no flattened fields), or create one.
796 if not isinstance(request, logging.DeleteLogRequest):
797 request = logging.DeleteLogRequest(request)
798 # If we have keyword arguments corresponding to fields on the
799 # request, apply these.
800 if log_name is not None:
801 request.log_name = log_name
802
803 # Wrap the RPC method; this adds retry and timeout information,
804 # and friendly error handling.
805 rpc = self._transport._wrapped_methods[self._transport.delete_log]
806
807 # Certain fields should be provided within the metadata header;
808 # add these here.
809 metadata = tuple(metadata) + (
810 gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)),
811 )
812
813 # Validate the universe domain.
814 self._validate_universe_domain()
815
816 # Send the request.
817 rpc(
818 request,
819 retry=retry,
820 timeout=timeout,
821 metadata=metadata,
822 )
823
824 def write_log_entries(
825 self,
826 request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None,
827 *,
828 log_name: Optional[str] = None,
829 resource: Optional[monitored_resource_pb2.MonitoredResource] = None,
830 labels: Optional[MutableMapping[str, str]] = None,
831 entries: Optional[MutableSequence[log_entry.LogEntry]] = None,
832 retry: OptionalRetry = gapic_v1.method.DEFAULT,
833 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
834 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
835 ) -> logging.WriteLogEntriesResponse:
836 r"""Writes log entries to Logging. This API method is the
837 only way to send log entries to Logging. This method is
838 used, directly or indirectly, by the Logging agent
839 (fluentd) and all logging libraries configured to use
840 Logging. A single request may contain log entries for a
841 maximum of 1000 different resources (projects,
842 organizations, billing accounts or folders)
843
844 .. code-block:: python
845
846 # This snippet has been automatically generated and should be regarded as a
847 # code template only.
848 # It will require modifications to work:
849 # - It may require correct/in-range values for request initialization.
850 # - It may require specifying regional endpoints when creating the service
851 # client as shown in:
852 # https://googleapis.dev/python/google-api-core/latest/client_options.html
853 from google.cloud import logging_v2
854
855 def sample_write_log_entries():
856 # Create a client
857 client = logging_v2.LoggingServiceV2Client()
858
859 # Initialize request argument(s)
860 entries = logging_v2.LogEntry()
861 entries.log_name = "log_name_value"
862
863 request = logging_v2.WriteLogEntriesRequest(
864 entries=entries,
865 )
866
867 # Make the request
868 response = client.write_log_entries(request=request)
869
870 # Handle the response
871 print(response)
872
873 Args:
874 request (Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]):
875 The request object. The parameters to WriteLogEntries.
876 log_name (str):
877 Optional. A default log resource name that is assigned
878 to all log entries in ``entries`` that do not specify a
879 value for ``log_name``:
880
881 - ``projects/[PROJECT_ID]/logs/[LOG_ID]``
882 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]``
883 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]``
884 - ``folders/[FOLDER_ID]/logs/[LOG_ID]``
885
886 ``[LOG_ID]`` must be URL-encoded. For example:
887
888 ::
889
890 "projects/my-project-id/logs/syslog"
891 "organizations/123/logs/cloudaudit.googleapis.com%2Factivity"
892
893 The permission ``logging.logEntries.create`` is needed
894 on each project, organization, billing account, or
895 folder that is receiving new log entries, whether the
896 resource is specified in ``logName`` or in an individual
897 log entry.
898
899 This corresponds to the ``log_name`` field
900 on the ``request`` instance; if ``request`` is provided, this
901 should not be set.
902 resource (google.api.monitored_resource_pb2.MonitoredResource):
903 Optional. A default monitored resource object that is
904 assigned to all log entries in ``entries`` that do not
905 specify a value for ``resource``. Example:
906
907 ::
908
909 { "type": "gce_instance",
910 "labels": {
911 "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
912
913 See [LogEntry][google.logging.v2.LogEntry].
914
915 This corresponds to the ``resource`` field
916 on the ``request`` instance; if ``request`` is provided, this
917 should not be set.
918 labels (MutableMapping[str, str]):
919 Optional. Default labels that are added to the
920 ``labels`` field of all log entries in ``entries``. If a
921 log entry already has a label with the same key as a
922 label in this parameter, then the log entry's label is
923 not changed. See [LogEntry][google.logging.v2.LogEntry].
924
925 This corresponds to the ``labels`` field
926 on the ``request`` instance; if ``request`` is provided, this
927 should not be set.
928 entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]):
929 Required. The log entries to send to Logging. The order
930 of log entries in this list does not matter. Values
931 supplied in this method's ``log_name``, ``resource``,
932 and ``labels`` fields are copied into those log entries
933 in this list that do not include values for their
934 corresponding fields. For more information, see the
935 [LogEntry][google.logging.v2.LogEntry] type.
936
937 If the ``timestamp`` or ``insert_id`` fields are missing
938 in log entries, then this method supplies the current
939 time or a unique identifier, respectively. The supplied
940 values are chosen so that, among the log entries that
941 did not supply their own values, the entries earlier in
942 the list will sort before the entries later in the list.
943 See the ``entries.list`` method.
944
945 Log entries with timestamps that are more than the `logs
946 retention
947 period <https://cloud.google.com/logging/quotas>`__ in
948 the past or more than 24 hours in the future will not be
949 available when calling ``entries.list``. However, those
950 log entries can still be `exported with
951 LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__.
952
953 To improve throughput and to avoid exceeding the `quota
954 limit <https://cloud.google.com/logging/quotas>`__ for
955 calls to ``entries.write``, you should try to include
956 several log entries in this list, rather than calling
957 this method for each individual log entry.
958
959 This corresponds to the ``entries`` field
960 on the ``request`` instance; if ``request`` is provided, this
961 should not be set.
962 retry (google.api_core.retry.Retry): Designation of what errors, if any,
963 should be retried.
964 timeout (float): The timeout for this request.
965 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
966 sent along with the request as metadata. Normally, each value must be of type `str`,
967 but for metadata keys ending with the suffix `-bin`, the corresponding values must
968 be of type `bytes`.
969
970 Returns:
971 google.cloud.logging_v2.types.WriteLogEntriesResponse:
972 Result returned from WriteLogEntries.
973 """
974 # Create or coerce a protobuf request object.
975 # - Quick check: If we got a request object, we should *not* have
976 # gotten any keyword arguments that map to the request.
977 flattened_params = [log_name, resource, labels, entries]
978 has_flattened_params = (
979 len([param for param in flattened_params if param is not None]) > 0
980 )
981 if request is not None and has_flattened_params:
982 raise ValueError(
983 "If the `request` argument is set, then none of "
984 "the individual field arguments should be set."
985 )
986
987 # - Use the request object if provided (there's no risk of modifying the input as
988 # there are no flattened fields), or create one.
989 if not isinstance(request, logging.WriteLogEntriesRequest):
990 request = logging.WriteLogEntriesRequest(request)
991 # If we have keyword arguments corresponding to fields on the
992 # request, apply these.
993 if log_name is not None:
994 request.log_name = log_name
995 if resource is not None:
996 request.resource = resource
997 if labels is not None:
998 request.labels = labels
999 if entries is not None:
1000 request.entries = entries
1001
1002 # Wrap the RPC method; this adds retry and timeout information,
1003 # and friendly error handling.
1004 rpc = self._transport._wrapped_methods[self._transport.write_log_entries]
1005
1006 # Validate the universe domain.
1007 self._validate_universe_domain()
1008
1009 # Send the request.
1010 response = rpc(
1011 request,
1012 retry=retry,
1013 timeout=timeout,
1014 metadata=metadata,
1015 )
1016
1017 # Done; return the response.
1018 return response
1019
1020 def list_log_entries(
1021 self,
1022 request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None,
1023 *,
1024 resource_names: Optional[MutableSequence[str]] = None,
1025 filter: Optional[str] = None,
1026 order_by: Optional[str] = None,
1027 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1028 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1029 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1030 ) -> pagers.ListLogEntriesPager:
1031 r"""Lists log entries. Use this method to retrieve log entries that
1032 originated from a project/folder/organization/billing account.
1033 For ways to export log entries, see `Exporting
1034 Logs <https://cloud.google.com/logging/docs/export>`__.
1035
1036 .. code-block:: python
1037
1038 # This snippet has been automatically generated and should be regarded as a
1039 # code template only.
1040 # It will require modifications to work:
1041 # - It may require correct/in-range values for request initialization.
1042 # - It may require specifying regional endpoints when creating the service
1043 # client as shown in:
1044 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1045 from google.cloud import logging_v2
1046
1047 def sample_list_log_entries():
1048 # Create a client
1049 client = logging_v2.LoggingServiceV2Client()
1050
1051 # Initialize request argument(s)
1052 request = logging_v2.ListLogEntriesRequest(
1053 resource_names=['resource_names_value1', 'resource_names_value2'],
1054 )
1055
1056 # Make the request
1057 page_result = client.list_log_entries(request=request)
1058
1059 # Handle the response
1060 for response in page_result:
1061 print(response)
1062
1063 Args:
1064 request (Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]):
1065 The request object. The parameters to ``ListLogEntries``.
1066 resource_names (MutableSequence[str]):
1067 Required. Names of one or more parent resources from
1068 which to retrieve log entries:
1069
1070 - ``projects/[PROJECT_ID]``
1071 - ``organizations/[ORGANIZATION_ID]``
1072 - ``billingAccounts/[BILLING_ACCOUNT_ID]``
1073 - ``folders/[FOLDER_ID]``
1074
1075 May alternatively be one or more views:
1076
1077 - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
1078 - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
1079 - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
1080 - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
1081
1082 Projects listed in the ``project_ids`` field are added
1083 to this list. A maximum of 100 resources may be
1084 specified in a single request.
1085
1086 This corresponds to the ``resource_names`` field
1087 on the ``request`` instance; if ``request`` is provided, this
1088 should not be set.
1089 filter (str):
1090 Optional. Only log entries that match the filter are
1091 returned. An empty filter matches all log entries in the
1092 resources listed in ``resource_names``. Referencing a
1093 parent resource that is not listed in ``resource_names``
1094 will cause the filter to return no results. The maximum
1095 length of a filter is 20,000 characters.
1096
1097 This corresponds to the ``filter`` field
1098 on the ``request`` instance; if ``request`` is provided, this
1099 should not be set.
1100 order_by (str):
1101 Optional. How the results should be sorted. Presently,
1102 the only permitted values are ``"timestamp asc"``
1103 (default) and ``"timestamp desc"``. The first option
1104 returns entries in order of increasing values of
1105 ``LogEntry.timestamp`` (oldest first), and the second
1106 option returns entries in order of decreasing timestamps
1107 (newest first). Entries with equal timestamps are
1108 returned in order of their ``insert_id`` values.
1109
1110 This corresponds to the ``order_by`` field
1111 on the ``request`` instance; if ``request`` is provided, this
1112 should not be set.
1113 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1114 should be retried.
1115 timeout (float): The timeout for this request.
1116 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1117 sent along with the request as metadata. Normally, each value must be of type `str`,
1118 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1119 be of type `bytes`.
1120
1121 Returns:
1122 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesPager:
1123 Result returned from ListLogEntries.
1124
1125 Iterating over this object will yield results and
1126 resolve additional pages automatically.
1127
1128 """
1129 # Create or coerce a protobuf request object.
1130 # - Quick check: If we got a request object, we should *not* have
1131 # gotten any keyword arguments that map to the request.
1132 flattened_params = [resource_names, filter, order_by]
1133 has_flattened_params = (
1134 len([param for param in flattened_params if param is not None]) > 0
1135 )
1136 if request is not None and has_flattened_params:
1137 raise ValueError(
1138 "If the `request` argument is set, then none of "
1139 "the individual field arguments should be set."
1140 )
1141
1142 # - Use the request object if provided (there's no risk of modifying the input as
1143 # there are no flattened fields), or create one.
1144 if not isinstance(request, logging.ListLogEntriesRequest):
1145 request = logging.ListLogEntriesRequest(request)
1146 # If we have keyword arguments corresponding to fields on the
1147 # request, apply these.
1148 if resource_names is not None:
1149 request.resource_names = resource_names
1150 if filter is not None:
1151 request.filter = filter
1152 if order_by is not None:
1153 request.order_by = order_by
1154
1155 # Wrap the RPC method; this adds retry and timeout information,
1156 # and friendly error handling.
1157 rpc = self._transport._wrapped_methods[self._transport.list_log_entries]
1158
1159 # Validate the universe domain.
1160 self._validate_universe_domain()
1161
1162 # Send the request.
1163 response = rpc(
1164 request,
1165 retry=retry,
1166 timeout=timeout,
1167 metadata=metadata,
1168 )
1169
1170 # This method is paged; wrap the response in a pager, which provides
1171 # an `__iter__` convenience method.
1172 response = pagers.ListLogEntriesPager(
1173 method=rpc,
1174 request=request,
1175 response=response,
1176 retry=retry,
1177 timeout=timeout,
1178 metadata=metadata,
1179 )
1180
1181 # Done; return the response.
1182 return response
1183
1184 def list_monitored_resource_descriptors(
1185 self,
1186 request: Optional[
1187 Union[logging.ListMonitoredResourceDescriptorsRequest, dict]
1188 ] = None,
1189 *,
1190 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1191 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1192 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1193 ) -> pagers.ListMonitoredResourceDescriptorsPager:
1194 r"""Lists the descriptors for monitored resource types
1195 used by Logging.
1196
1197 .. code-block:: python
1198
1199 # This snippet has been automatically generated and should be regarded as a
1200 # code template only.
1201 # It will require modifications to work:
1202 # - It may require correct/in-range values for request initialization.
1203 # - It may require specifying regional endpoints when creating the service
1204 # client as shown in:
1205 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1206 from google.cloud import logging_v2
1207
1208 def sample_list_monitored_resource_descriptors():
1209 # Create a client
1210 client = logging_v2.LoggingServiceV2Client()
1211
1212 # Initialize request argument(s)
1213 request = logging_v2.ListMonitoredResourceDescriptorsRequest(
1214 )
1215
1216 # Make the request
1217 page_result = client.list_monitored_resource_descriptors(request=request)
1218
1219 # Handle the response
1220 for response in page_result:
1221 print(response)
1222
1223 Args:
1224 request (Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]):
1225 The request object. The parameters to
1226 ListMonitoredResourceDescriptors
1227 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1228 should be retried.
1229 timeout (float): The timeout for this request.
1230 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1231 sent along with the request as metadata. Normally, each value must be of type `str`,
1232 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1233 be of type `bytes`.
1234
1235 Returns:
1236 google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsPager:
1237 Result returned from
1238 ListMonitoredResourceDescriptors.
1239 Iterating over this object will yield
1240 results and resolve additional pages
1241 automatically.
1242
1243 """
1244 # Create or coerce a protobuf request object.
1245 # - Use the request object if provided (there's no risk of modifying the input as
1246 # there are no flattened fields), or create one.
1247 if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest):
1248 request = logging.ListMonitoredResourceDescriptorsRequest(request)
1249
1250 # Wrap the RPC method; this adds retry and timeout information,
1251 # and friendly error handling.
1252 rpc = self._transport._wrapped_methods[
1253 self._transport.list_monitored_resource_descriptors
1254 ]
1255
1256 # Validate the universe domain.
1257 self._validate_universe_domain()
1258
1259 # Send the request.
1260 response = rpc(
1261 request,
1262 retry=retry,
1263 timeout=timeout,
1264 metadata=metadata,
1265 )
1266
1267 # This method is paged; wrap the response in a pager, which provides
1268 # an `__iter__` convenience method.
1269 response = pagers.ListMonitoredResourceDescriptorsPager(
1270 method=rpc,
1271 request=request,
1272 response=response,
1273 retry=retry,
1274 timeout=timeout,
1275 metadata=metadata,
1276 )
1277
1278 # Done; return the response.
1279 return response
1280
1281 def list_logs(
1282 self,
1283 request: Optional[Union[logging.ListLogsRequest, dict]] = None,
1284 *,
1285 parent: Optional[str] = None,
1286 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1287 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1288 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1289 ) -> pagers.ListLogsPager:
1290 r"""Lists the logs in projects, organizations, folders,
1291 or billing accounts. Only logs that have entries are
1292 listed.
1293
1294 .. code-block:: python
1295
1296 # This snippet has been automatically generated and should be regarded as a
1297 # code template only.
1298 # It will require modifications to work:
1299 # - It may require correct/in-range values for request initialization.
1300 # - It may require specifying regional endpoints when creating the service
1301 # client as shown in:
1302 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1303 from google.cloud import logging_v2
1304
1305 def sample_list_logs():
1306 # Create a client
1307 client = logging_v2.LoggingServiceV2Client()
1308
1309 # Initialize request argument(s)
1310 request = logging_v2.ListLogsRequest(
1311 parent="parent_value",
1312 )
1313
1314 # Make the request
1315 page_result = client.list_logs(request=request)
1316
1317 # Handle the response
1318 for response in page_result:
1319 print(response)
1320
1321 Args:
1322 request (Union[google.cloud.logging_v2.types.ListLogsRequest, dict]):
1323 The request object. The parameters to ListLogs.
1324 parent (str):
1325 Required. The resource name to list logs for:
1326
1327 - ``projects/[PROJECT_ID]``
1328 - ``organizations/[ORGANIZATION_ID]``
1329 - ``billingAccounts/[BILLING_ACCOUNT_ID]``
1330 - ``folders/[FOLDER_ID]``
1331
1332 This corresponds to the ``parent`` field
1333 on the ``request`` instance; if ``request`` is provided, this
1334 should not be set.
1335 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1336 should be retried.
1337 timeout (float): The timeout for this request.
1338 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1339 sent along with the request as metadata. Normally, each value must be of type `str`,
1340 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1341 be of type `bytes`.
1342
1343 Returns:
1344 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsPager:
1345 Result returned from ListLogs.
1346
1347 Iterating over this object will yield
1348 results and resolve additional pages
1349 automatically.
1350
1351 """
1352 # Create or coerce a protobuf request object.
1353 # - Quick check: If we got a request object, we should *not* have
1354 # gotten any keyword arguments that map to the request.
1355 flattened_params = [parent]
1356 has_flattened_params = (
1357 len([param for param in flattened_params if param is not None]) > 0
1358 )
1359 if request is not None and has_flattened_params:
1360 raise ValueError(
1361 "If the `request` argument is set, then none of "
1362 "the individual field arguments should be set."
1363 )
1364
1365 # - Use the request object if provided (there's no risk of modifying the input as
1366 # there are no flattened fields), or create one.
1367 if not isinstance(request, logging.ListLogsRequest):
1368 request = logging.ListLogsRequest(request)
1369 # If we have keyword arguments corresponding to fields on the
1370 # request, apply these.
1371 if parent is not None:
1372 request.parent = parent
1373
1374 # Wrap the RPC method; this adds retry and timeout information,
1375 # and friendly error handling.
1376 rpc = self._transport._wrapped_methods[self._transport.list_logs]
1377
1378 # Certain fields should be provided within the metadata header;
1379 # add these here.
1380 metadata = tuple(metadata) + (
1381 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1382 )
1383
1384 # Validate the universe domain.
1385 self._validate_universe_domain()
1386
1387 # Send the request.
1388 response = rpc(
1389 request,
1390 retry=retry,
1391 timeout=timeout,
1392 metadata=metadata,
1393 )
1394
1395 # This method is paged; wrap the response in a pager, which provides
1396 # an `__iter__` convenience method.
1397 response = pagers.ListLogsPager(
1398 method=rpc,
1399 request=request,
1400 response=response,
1401 retry=retry,
1402 timeout=timeout,
1403 metadata=metadata,
1404 )
1405
1406 # Done; return the response.
1407 return response
1408
1409 def tail_log_entries(
1410 self,
1411 requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None,
1412 *,
1413 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1414 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1415 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1416 ) -> Iterable[logging.TailLogEntriesResponse]:
1417 r"""Streaming read of log entries as they are ingested.
1418 Until the stream is terminated, it will continue reading
1419 logs.
1420
1421 .. code-block:: python
1422
1423 # This snippet has been automatically generated and should be regarded as a
1424 # code template only.
1425 # It will require modifications to work:
1426 # - It may require correct/in-range values for request initialization.
1427 # - It may require specifying regional endpoints when creating the service
1428 # client as shown in:
1429 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1430 from google.cloud import logging_v2
1431
1432 def sample_tail_log_entries():
1433 # Create a client
1434 client = logging_v2.LoggingServiceV2Client()
1435
1436 # Initialize request argument(s)
1437 request = logging_v2.TailLogEntriesRequest(
1438 resource_names=['resource_names_value1', 'resource_names_value2'],
1439 )
1440
1441 # This method expects an iterator which contains
1442 # 'logging_v2.TailLogEntriesRequest' objects
1443 # Here we create a generator that yields a single `request` for
1444 # demonstrative purposes.
1445 requests = [request]
1446
1447 def request_generator():
1448 for request in requests:
1449 yield request
1450
1451 # Make the request
1452 stream = client.tail_log_entries(requests=request_generator())
1453
1454 # Handle the response
1455 for response in stream:
1456 print(response)
1457
1458 Args:
1459 requests (Iterator[google.cloud.logging_v2.types.TailLogEntriesRequest]):
1460 The request object iterator. The parameters to ``TailLogEntries``.
1461 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1462 should be retried.
1463 timeout (float): The timeout for this request.
1464 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1465 sent along with the request as metadata. Normally, each value must be of type `str`,
1466 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1467 be of type `bytes`.
1468
1469 Returns:
1470 Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]:
1471 Result returned from TailLogEntries.
1472 """
1473
1474 # Wrap the RPC method; this adds retry and timeout information,
1475 # and friendly error handling.
1476 rpc = self._transport._wrapped_methods[self._transport.tail_log_entries]
1477
1478 # Validate the universe domain.
1479 self._validate_universe_domain()
1480
1481 # Send the request.
1482 response = rpc(
1483 requests,
1484 retry=retry,
1485 timeout=timeout,
1486 metadata=metadata,
1487 )
1488
1489 # Done; return the response.
1490 return response
1491
1492 def __enter__(self) -> "LoggingServiceV2Client":
1493 return self
1494
1495 def __exit__(self, type, value, traceback):
1496 """Releases underlying transport's resources.
1497
1498 .. warning::
1499 ONLY use as a context manager if the transport is NOT shared
1500 with other clients! Exiting the with block will CLOSE the transport
1501 and may cause errors in other clients!
1502 """
1503 self.transport.close()
1504
1505 def list_operations(
1506 self,
1507 request: Optional[operations_pb2.ListOperationsRequest] = None,
1508 *,
1509 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1510 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1511 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1512 ) -> operations_pb2.ListOperationsResponse:
1513 r"""Lists operations that match the specified filter in the request.
1514
1515 Args:
1516 request (:class:`~.operations_pb2.ListOperationsRequest`):
1517 The request object. Request message for
1518 `ListOperations` method.
1519 retry (google.api_core.retry.Retry): Designation of what errors,
1520 if any, should be retried.
1521 timeout (float): The timeout for this request.
1522 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1523 sent along with the request as metadata. Normally, each value must be of type `str`,
1524 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1525 be of type `bytes`.
1526 Returns:
1527 ~.operations_pb2.ListOperationsResponse:
1528 Response message for ``ListOperations`` method.
1529 """
1530 # Create or coerce a protobuf request object.
1531 # The request isn't a proto-plus wrapped type,
1532 # so it must be constructed via keyword expansion.
1533 if isinstance(request, dict):
1534 request = operations_pb2.ListOperationsRequest(**request)
1535
1536 # Wrap the RPC method; this adds retry and timeout information,
1537 # and friendly error handling.
1538 rpc = self._transport._wrapped_methods[self._transport.list_operations]
1539
1540 # Certain fields should be provided within the metadata header;
1541 # add these here.
1542 metadata = tuple(metadata) + (
1543 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1544 )
1545
1546 # Validate the universe domain.
1547 self._validate_universe_domain()
1548
1549 try:
1550 # Send the request.
1551 response = rpc(
1552 request,
1553 retry=retry,
1554 timeout=timeout,
1555 metadata=metadata,
1556 )
1557
1558 # Done; return the response.
1559 return response
1560 except core_exceptions.GoogleAPICallError as e:
1561 self._add_cred_info_for_auth_errors(e)
1562 raise e
1563
1564 def get_operation(
1565 self,
1566 request: Optional[operations_pb2.GetOperationRequest] = None,
1567 *,
1568 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1569 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1570 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1571 ) -> operations_pb2.Operation:
1572 r"""Gets the latest state of a long-running operation.
1573
1574 Args:
1575 request (:class:`~.operations_pb2.GetOperationRequest`):
1576 The request object. Request message for
1577 `GetOperation` method.
1578 retry (google.api_core.retry.Retry): Designation of what errors,
1579 if any, should be retried.
1580 timeout (float): The timeout for this request.
1581 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1582 sent along with the request as metadata. Normally, each value must be of type `str`,
1583 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1584 be of type `bytes`.
1585 Returns:
1586 ~.operations_pb2.Operation:
1587 An ``Operation`` object.
1588 """
1589 # Create or coerce a protobuf request object.
1590 # The request isn't a proto-plus wrapped type,
1591 # so it must be constructed via keyword expansion.
1592 if isinstance(request, dict):
1593 request = operations_pb2.GetOperationRequest(**request)
1594
1595 # Wrap the RPC method; this adds retry and timeout information,
1596 # and friendly error handling.
1597 rpc = self._transport._wrapped_methods[self._transport.get_operation]
1598
1599 # Certain fields should be provided within the metadata header;
1600 # add these here.
1601 metadata = tuple(metadata) + (
1602 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1603 )
1604
1605 # Validate the universe domain.
1606 self._validate_universe_domain()
1607
1608 try:
1609 # Send the request.
1610 response = rpc(
1611 request,
1612 retry=retry,
1613 timeout=timeout,
1614 metadata=metadata,
1615 )
1616
1617 # Done; return the response.
1618 return response
1619 except core_exceptions.GoogleAPICallError as e:
1620 self._add_cred_info_for_auth_errors(e)
1621 raise e
1622
1623 def cancel_operation(
1624 self,
1625 request: Optional[operations_pb2.CancelOperationRequest] = None,
1626 *,
1627 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1628 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1629 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1630 ) -> None:
1631 r"""Starts asynchronous cancellation on a long-running operation.
1632
1633 The server makes a best effort to cancel the operation, but success
1634 is not guaranteed. If the server doesn't support this method, it returns
1635 `google.rpc.Code.UNIMPLEMENTED`.
1636
1637 Args:
1638 request (:class:`~.operations_pb2.CancelOperationRequest`):
1639 The request object. Request message for
1640 `CancelOperation` method.
1641 retry (google.api_core.retry.Retry): Designation of what errors,
1642 if any, should be retried.
1643 timeout (float): The timeout for this request.
1644 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1645 sent along with the request as metadata. Normally, each value must be of type `str`,
1646 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1647 be of type `bytes`.
1648 Returns:
1649 None
1650 """
1651 # Create or coerce a protobuf request object.
1652 # The request isn't a proto-plus wrapped type,
1653 # so it must be constructed via keyword expansion.
1654 if isinstance(request, dict):
1655 request = operations_pb2.CancelOperationRequest(**request)
1656
1657 # Wrap the RPC method; this adds retry and timeout information,
1658 # and friendly error handling.
1659 rpc = self._transport._wrapped_methods[self._transport.cancel_operation]
1660
1661 # Certain fields should be provided within the metadata header;
1662 # add these here.
1663 metadata = tuple(metadata) + (
1664 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1665 )
1666
1667 # Validate the universe domain.
1668 self._validate_universe_domain()
1669
1670 # Send the request.
1671 rpc(
1672 request,
1673 retry=retry,
1674 timeout=timeout,
1675 metadata=metadata,
1676 )
1677
1678
1679DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1680 gapic_version=package_version.__version__
1681)
1682
1683if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
1684 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
1685
1686__all__ = ("LoggingServiceV2Client",)