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