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