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