Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/logging_v2/services/logging_service_v2/client.py: 37%
240 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:45 +0000
1# -*- coding: utf-8 -*-
2# Copyright 2023 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
17import os
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 Iterable,
26 Iterator,
27 Sequence,
28 Tuple,
29 Type,
30 Union,
31 cast,
32)
34from google.cloud.logging_v2 import gapic_version as package_version
36from google.api_core import client_options as client_options_lib
37from google.api_core import exceptions as core_exceptions
38from google.api_core import gapic_v1
39from google.api_core import retry as retries
40from google.auth import credentials as ga_credentials # type: ignore
41from google.auth.transport import mtls # type: ignore
42from google.auth.transport.grpc import SslCredentials # type: ignore
43from google.auth.exceptions import MutualTLSChannelError # type: ignore
44from google.oauth2 import service_account # type: ignore
46try:
47 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
48except AttributeError: # pragma: NO COVER
49 OptionalRetry = Union[retries.Retry, object] # type: ignore
51from google.api import monitored_resource_pb2 # type: ignore
52from google.cloud.logging_v2.services.logging_service_v2 import pagers
53from google.cloud.logging_v2.types import log_entry
54from google.cloud.logging_v2.types import logging
55from google.longrunning import operations_pb2 # type: ignore
56from .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO
57from .transports.grpc import LoggingServiceV2GrpcTransport
58from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport
61class LoggingServiceV2ClientMeta(type):
62 """Metaclass for the LoggingServiceV2 client.
64 This provides class-level methods for building and retrieving
65 support objects (e.g. transport) without polluting the client instance
66 objects.
67 """
69 _transport_registry = (
70 OrderedDict()
71 ) # type: Dict[str, Type[LoggingServiceV2Transport]]
72 _transport_registry["grpc"] = LoggingServiceV2GrpcTransport
73 _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport
75 def get_transport_class(
76 cls,
77 label: Optional[str] = None,
78 ) -> Type[LoggingServiceV2Transport]:
79 """Returns an appropriate transport class.
81 Args:
82 label: The name of the desired transport. If none is
83 provided, then the first transport in the registry is used.
85 Returns:
86 The transport class to use.
87 """
88 # If a specific transport is requested, return that one.
89 if label:
90 return cls._transport_registry[label]
92 # No transport is requested; return the default (that is, the first one
93 # in the dictionary).
94 return next(iter(cls._transport_registry.values()))
97class LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta):
98 """Service for ingesting and querying logs."""
100 @staticmethod
101 def _get_default_mtls_endpoint(api_endpoint):
102 """Converts api endpoint to mTLS endpoint.
104 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
105 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
106 Args:
107 api_endpoint (Optional[str]): the api endpoint to convert.
108 Returns:
109 str: converted mTLS api endpoint.
110 """
111 if not api_endpoint:
112 return api_endpoint
114 mtls_endpoint_re = re.compile(
115 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
116 )
118 m = mtls_endpoint_re.match(api_endpoint)
119 name, mtls, sandbox, googledomain = m.groups()
120 if mtls or not googledomain:
121 return api_endpoint
123 if sandbox:
124 return api_endpoint.replace(
125 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
126 )
128 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
130 DEFAULT_ENDPOINT = "logging.googleapis.com"
131 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
132 DEFAULT_ENDPOINT
133 )
135 @classmethod
136 def from_service_account_info(cls, info: dict, *args, **kwargs):
137 """Creates an instance of this client using the provided credentials
138 info.
140 Args:
141 info (dict): The service account private key info.
142 args: Additional arguments to pass to the constructor.
143 kwargs: Additional arguments to pass to the constructor.
145 Returns:
146 LoggingServiceV2Client: The constructed client.
147 """
148 credentials = service_account.Credentials.from_service_account_info(info)
149 kwargs["credentials"] = credentials
150 return cls(*args, **kwargs)
152 @classmethod
153 def from_service_account_file(cls, filename: str, *args, **kwargs):
154 """Creates an instance of this client using the provided credentials
155 file.
157 Args:
158 filename (str): The path to the service account private key json
159 file.
160 args: Additional arguments to pass to the constructor.
161 kwargs: Additional arguments to pass to the constructor.
163 Returns:
164 LoggingServiceV2Client: The constructed client.
165 """
166 credentials = service_account.Credentials.from_service_account_file(filename)
167 kwargs["credentials"] = credentials
168 return cls(*args, **kwargs)
170 from_service_account_json = from_service_account_file
172 @property
173 def transport(self) -> LoggingServiceV2Transport:
174 """Returns the transport used by the client instance.
176 Returns:
177 LoggingServiceV2Transport: The transport used by the client
178 instance.
179 """
180 return self._transport
182 @staticmethod
183 def log_path(
184 project: str,
185 log: str,
186 ) -> str:
187 """Returns a fully-qualified log string."""
188 return "projects/{project}/logs/{log}".format(
189 project=project,
190 log=log,
191 )
193 @staticmethod
194 def parse_log_path(path: str) -> Dict[str, str]:
195 """Parses a log path into its component segments."""
196 m = re.match(r"^projects/(?P<project>.+?)/logs/(?P<log>.+?)$", path)
197 return m.groupdict() if m else {}
199 @staticmethod
200 def common_billing_account_path(
201 billing_account: str,
202 ) -> str:
203 """Returns a fully-qualified billing_account string."""
204 return "billingAccounts/{billing_account}".format(
205 billing_account=billing_account,
206 )
208 @staticmethod
209 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
210 """Parse a billing_account path into its component segments."""
211 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
212 return m.groupdict() if m else {}
214 @staticmethod
215 def common_folder_path(
216 folder: str,
217 ) -> str:
218 """Returns a fully-qualified folder string."""
219 return "folders/{folder}".format(
220 folder=folder,
221 )
223 @staticmethod
224 def parse_common_folder_path(path: str) -> Dict[str, str]:
225 """Parse a folder path into its component segments."""
226 m = re.match(r"^folders/(?P<folder>.+?)$", path)
227 return m.groupdict() if m else {}
229 @staticmethod
230 def common_organization_path(
231 organization: str,
232 ) -> str:
233 """Returns a fully-qualified organization string."""
234 return "organizations/{organization}".format(
235 organization=organization,
236 )
238 @staticmethod
239 def parse_common_organization_path(path: str) -> Dict[str, str]:
240 """Parse a organization path into its component segments."""
241 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
242 return m.groupdict() if m else {}
244 @staticmethod
245 def common_project_path(
246 project: str,
247 ) -> str:
248 """Returns a fully-qualified project string."""
249 return "projects/{project}".format(
250 project=project,
251 )
253 @staticmethod
254 def parse_common_project_path(path: str) -> Dict[str, str]:
255 """Parse a project path into its component segments."""
256 m = re.match(r"^projects/(?P<project>.+?)$", path)
257 return m.groupdict() if m else {}
259 @staticmethod
260 def common_location_path(
261 project: str,
262 location: str,
263 ) -> str:
264 """Returns a fully-qualified location string."""
265 return "projects/{project}/locations/{location}".format(
266 project=project,
267 location=location,
268 )
270 @staticmethod
271 def parse_common_location_path(path: str) -> Dict[str, str]:
272 """Parse a location path into its component segments."""
273 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
274 return m.groupdict() if m else {}
276 @classmethod
277 def get_mtls_endpoint_and_cert_source(
278 cls, client_options: Optional[client_options_lib.ClientOptions] = None
279 ):
280 """Return the API endpoint and client cert source for mutual TLS.
282 The client cert source is determined in the following order:
283 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
284 client cert source is None.
285 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
286 default client cert source exists, use the default one; otherwise the client cert
287 source is None.
289 The API endpoint is determined in the following order:
290 (1) if `client_options.api_endpoint` if provided, use the provided one.
291 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
292 default mTLS endpoint; if the environment variable is "never", use the default API
293 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
294 use the default API endpoint.
296 More details can be found at https://google.aip.dev/auth/4114.
298 Args:
299 client_options (google.api_core.client_options.ClientOptions): Custom options for the
300 client. Only the `api_endpoint` and `client_cert_source` properties may be used
301 in this method.
303 Returns:
304 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
305 client cert source to use.
307 Raises:
308 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
309 """
310 if client_options is None:
311 client_options = client_options_lib.ClientOptions()
312 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
313 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
314 if use_client_cert not in ("true", "false"):
315 raise ValueError(
316 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
317 )
318 if use_mtls_endpoint not in ("auto", "never", "always"):
319 raise MutualTLSChannelError(
320 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
321 )
323 # Figure out the client cert source to use.
324 client_cert_source = None
325 if use_client_cert == "true":
326 if client_options.client_cert_source:
327 client_cert_source = client_options.client_cert_source
328 elif mtls.has_default_client_cert_source():
329 client_cert_source = mtls.default_client_cert_source()
331 # Figure out which api endpoint to use.
332 if client_options.api_endpoint is not None:
333 api_endpoint = client_options.api_endpoint
334 elif use_mtls_endpoint == "always" or (
335 use_mtls_endpoint == "auto" and client_cert_source
336 ):
337 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
338 else:
339 api_endpoint = cls.DEFAULT_ENDPOINT
341 return api_endpoint, client_cert_source
343 def __init__(
344 self,
345 *,
346 credentials: Optional[ga_credentials.Credentials] = None,
347 transport: Optional[Union[str, LoggingServiceV2Transport]] = None,
348 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
349 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
350 ) -> None:
351 """Instantiates the logging service v2 client.
353 Args:
354 credentials (Optional[google.auth.credentials.Credentials]): The
355 authorization credentials to attach to requests. These
356 credentials identify the application to the service; if none
357 are specified, the client will attempt to ascertain the
358 credentials from the environment.
359 transport (Union[str, LoggingServiceV2Transport]): The
360 transport to use. If set to None, a transport is chosen
361 automatically.
362 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
363 client. It won't take effect if a ``transport`` instance is provided.
364 (1) The ``api_endpoint`` property can be used to override the
365 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
366 environment variable can also be used to override the endpoint:
367 "always" (always use the default mTLS endpoint), "never" (always
368 use the default regular endpoint) and "auto" (auto switch to the
369 default mTLS endpoint if client certificate is present, this is
370 the default value). However, the ``api_endpoint`` property takes
371 precedence if provided.
372 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
373 is "true", then the ``client_cert_source`` property can be used
374 to provide client certificate for mutual TLS transport. If
375 not provided, the default SSL client certificate will be used if
376 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
377 set, no client certificate will be used.
378 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
379 The client info used to send a user-agent string along with
380 API requests. If ``None``, then default info will be used.
381 Generally, you only need to set this if you're developing
382 your own client library.
384 Raises:
385 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
386 creation failed for any reason.
387 """
388 if isinstance(client_options, dict):
389 client_options = client_options_lib.from_dict(client_options)
390 if client_options is None:
391 client_options = client_options_lib.ClientOptions()
392 client_options = cast(client_options_lib.ClientOptions, client_options)
394 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
395 client_options
396 )
398 api_key_value = getattr(client_options, "api_key", None)
399 if api_key_value and credentials:
400 raise ValueError(
401 "client_options.api_key and credentials are mutually exclusive"
402 )
404 # Save or instantiate the transport.
405 # Ordinarily, we provide the transport, but allowing a custom transport
406 # instance provides an extensibility point for unusual situations.
407 if isinstance(transport, LoggingServiceV2Transport):
408 # transport is a LoggingServiceV2Transport instance.
409 if credentials or client_options.credentials_file or api_key_value:
410 raise ValueError(
411 "When providing a transport instance, "
412 "provide its credentials directly."
413 )
414 if client_options.scopes:
415 raise ValueError(
416 "When providing a transport instance, provide its scopes "
417 "directly."
418 )
419 self._transport = transport
420 else:
421 import google.auth._default # type: ignore
423 if api_key_value and hasattr(
424 google.auth._default, "get_api_key_credentials"
425 ):
426 credentials = google.auth._default.get_api_key_credentials(
427 api_key_value
428 )
430 Transport = type(self).get_transport_class(transport)
431 self._transport = Transport(
432 credentials=credentials,
433 credentials_file=client_options.credentials_file,
434 host=api_endpoint,
435 scopes=client_options.scopes,
436 client_cert_source_for_mtls=client_cert_source_func,
437 quota_project_id=client_options.quota_project_id,
438 client_info=client_info,
439 always_use_jwt_access=True,
440 api_audience=client_options.api_audience,
441 )
443 def delete_log(
444 self,
445 request: Optional[Union[logging.DeleteLogRequest, dict]] = None,
446 *,
447 log_name: Optional[str] = None,
448 retry: OptionalRetry = gapic_v1.method.DEFAULT,
449 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
450 metadata: Sequence[Tuple[str, str]] = (),
451 ) -> None:
452 r"""Deletes all the log entries in a log for the \_Default Log
453 Bucket. The log reappears if it receives new entries. Log
454 entries written shortly before the delete operation might not be
455 deleted. Entries received after the delete operation with a
456 timestamp before the operation will be deleted.
458 .. code-block:: python
460 # This snippet has been automatically generated and should be regarded as a
461 # code template only.
462 # It will require modifications to work:
463 # - It may require correct/in-range values for request initialization.
464 # - It may require specifying regional endpoints when creating the service
465 # client as shown in:
466 # https://googleapis.dev/python/google-api-core/latest/client_options.html
467 from google.cloud import logging_v2
469 def sample_delete_log():
470 # Create a client
471 client = logging_v2.LoggingServiceV2Client()
473 # Initialize request argument(s)
474 request = logging_v2.DeleteLogRequest(
475 log_name="log_name_value",
476 )
478 # Make the request
479 client.delete_log(request=request)
481 Args:
482 request (Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]):
483 The request object. The parameters to DeleteLog.
484 log_name (str):
485 Required. The resource name of the log to delete:
487 - ``projects/[PROJECT_ID]/logs/[LOG_ID]``
488 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]``
489 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]``
490 - ``folders/[FOLDER_ID]/logs/[LOG_ID]``
492 ``[LOG_ID]`` must be URL-encoded. For example,
493 ``"projects/my-project-id/logs/syslog"``,
494 ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``.
496 For more information about log names, see
497 [LogEntry][google.logging.v2.LogEntry].
499 This corresponds to the ``log_name`` field
500 on the ``request`` instance; if ``request`` is provided, this
501 should not be set.
502 retry (google.api_core.retry.Retry): Designation of what errors, if any,
503 should be retried.
504 timeout (float): The timeout for this request.
505 metadata (Sequence[Tuple[str, str]]): Strings which should be
506 sent along with the request as metadata.
507 """
508 # Create or coerce a protobuf request object.
509 # Quick check: If we got a request object, we should *not* have
510 # gotten any keyword arguments that map to the request.
511 has_flattened_params = any([log_name])
512 if request is not None and has_flattened_params:
513 raise ValueError(
514 "If the `request` argument is set, then none of "
515 "the individual field arguments should be set."
516 )
518 # Minor optimization to avoid making a copy if the user passes
519 # in a logging.DeleteLogRequest.
520 # There's no risk of modifying the input as we've already verified
521 # there are no flattened fields.
522 if not isinstance(request, logging.DeleteLogRequest):
523 request = logging.DeleteLogRequest(request)
524 # If we have keyword arguments corresponding to fields on the
525 # request, apply these.
526 if log_name is not None:
527 request.log_name = log_name
529 # Wrap the RPC method; this adds retry and timeout information,
530 # and friendly error handling.
531 rpc = self._transport._wrapped_methods[self._transport.delete_log]
533 # Certain fields should be provided within the metadata header;
534 # add these here.
535 metadata = tuple(metadata) + (
536 gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)),
537 )
539 # Send the request.
540 rpc(
541 request,
542 retry=retry,
543 timeout=timeout,
544 metadata=metadata,
545 )
547 def write_log_entries(
548 self,
549 request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None,
550 *,
551 log_name: Optional[str] = None,
552 resource: Optional[monitored_resource_pb2.MonitoredResource] = None,
553 labels: Optional[MutableMapping[str, str]] = None,
554 entries: Optional[MutableSequence[log_entry.LogEntry]] = None,
555 retry: OptionalRetry = gapic_v1.method.DEFAULT,
556 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
557 metadata: Sequence[Tuple[str, str]] = (),
558 ) -> logging.WriteLogEntriesResponse:
559 r"""Writes log entries to Logging. This API method is the
560 only way to send log entries to Logging. This method is
561 used, directly or indirectly, by the Logging agent
562 (fluentd) and all logging libraries configured to use
563 Logging. A single request may contain log entries for a
564 maximum of 1000 different resources (projects,
565 organizations, billing accounts or folders)
567 .. code-block:: python
569 # This snippet has been automatically generated and should be regarded as a
570 # code template only.
571 # It will require modifications to work:
572 # - It may require correct/in-range values for request initialization.
573 # - It may require specifying regional endpoints when creating the service
574 # client as shown in:
575 # https://googleapis.dev/python/google-api-core/latest/client_options.html
576 from google.cloud import logging_v2
578 def sample_write_log_entries():
579 # Create a client
580 client = logging_v2.LoggingServiceV2Client()
582 # Initialize request argument(s)
583 entries = logging_v2.LogEntry()
584 entries.log_name = "log_name_value"
586 request = logging_v2.WriteLogEntriesRequest(
587 entries=entries,
588 )
590 # Make the request
591 response = client.write_log_entries(request=request)
593 # Handle the response
594 print(response)
596 Args:
597 request (Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]):
598 The request object. The parameters to WriteLogEntries.
599 log_name (str):
600 Optional. A default log resource name that is assigned
601 to all log entries in ``entries`` that do not specify a
602 value for ``log_name``:
604 - ``projects/[PROJECT_ID]/logs/[LOG_ID]``
605 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]``
606 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]``
607 - ``folders/[FOLDER_ID]/logs/[LOG_ID]``
609 ``[LOG_ID]`` must be URL-encoded. For example:
611 ::
613 "projects/my-project-id/logs/syslog"
614 "organizations/123/logs/cloudaudit.googleapis.com%2Factivity"
616 The permission ``logging.logEntries.create`` is needed
617 on each project, organization, billing account, or
618 folder that is receiving new log entries, whether the
619 resource is specified in ``logName`` or in an individual
620 log entry.
622 This corresponds to the ``log_name`` field
623 on the ``request`` instance; if ``request`` is provided, this
624 should not be set.
625 resource (google.api.monitored_resource_pb2.MonitoredResource):
626 Optional. A default monitored resource object that is
627 assigned to all log entries in ``entries`` that do not
628 specify a value for ``resource``. Example:
630 ::
632 { "type": "gce_instance",
633 "labels": {
634 "zone": "us-central1-a", "instance_id": "00000000000000000000" }}
636 See [LogEntry][google.logging.v2.LogEntry].
638 This corresponds to the ``resource`` field
639 on the ``request`` instance; if ``request`` is provided, this
640 should not be set.
641 labels (MutableMapping[str, str]):
642 Optional. Default labels that are added to the
643 ``labels`` field of all log entries in ``entries``. If a
644 log entry already has a label with the same key as a
645 label in this parameter, then the log entry's label is
646 not changed. See [LogEntry][google.logging.v2.LogEntry].
648 This corresponds to the ``labels`` field
649 on the ``request`` instance; if ``request`` is provided, this
650 should not be set.
651 entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]):
652 Required. The log entries to send to Logging. The order
653 of log entries in this list does not matter. Values
654 supplied in this method's ``log_name``, ``resource``,
655 and ``labels`` fields are copied into those log entries
656 in this list that do not include values for their
657 corresponding fields. For more information, see the
658 [LogEntry][google.logging.v2.LogEntry] type.
660 If the ``timestamp`` or ``insert_id`` fields are missing
661 in log entries, then this method supplies the current
662 time or a unique identifier, respectively. The supplied
663 values are chosen so that, among the log entries that
664 did not supply their own values, the entries earlier in
665 the list will sort before the entries later in the list.
666 See the ``entries.list`` method.
668 Log entries with timestamps that are more than the `logs
669 retention
670 period <https://cloud.google.com/logging/quotas>`__ in
671 the past or more than 24 hours in the future will not be
672 available when calling ``entries.list``. However, those
673 log entries can still be `exported with
674 LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__.
676 To improve throughput and to avoid exceeding the `quota
677 limit <https://cloud.google.com/logging/quotas>`__ for
678 calls to ``entries.write``, you should try to include
679 several log entries in this list, rather than calling
680 this method for each individual log entry.
682 This corresponds to the ``entries`` field
683 on the ``request`` instance; if ``request`` is provided, this
684 should not be set.
685 retry (google.api_core.retry.Retry): Designation of what errors, if any,
686 should be retried.
687 timeout (float): The timeout for this request.
688 metadata (Sequence[Tuple[str, str]]): Strings which should be
689 sent along with the request as metadata.
691 Returns:
692 google.cloud.logging_v2.types.WriteLogEntriesResponse:
693 Result returned from WriteLogEntries.
694 """
695 # Create or coerce a protobuf request object.
696 # Quick check: If we got a request object, we should *not* have
697 # gotten any keyword arguments that map to the request.
698 has_flattened_params = any([log_name, resource, labels, entries])
699 if request is not None and has_flattened_params:
700 raise ValueError(
701 "If the `request` argument is set, then none of "
702 "the individual field arguments should be set."
703 )
705 # Minor optimization to avoid making a copy if the user passes
706 # in a logging.WriteLogEntriesRequest.
707 # There's no risk of modifying the input as we've already verified
708 # there are no flattened fields.
709 if not isinstance(request, logging.WriteLogEntriesRequest):
710 request = logging.WriteLogEntriesRequest(request)
711 # If we have keyword arguments corresponding to fields on the
712 # request, apply these.
713 if log_name is not None:
714 request.log_name = log_name
715 if resource is not None:
716 request.resource = resource
717 if labels is not None:
718 request.labels = labels
719 if entries is not None:
720 request.entries = entries
722 # Wrap the RPC method; this adds retry and timeout information,
723 # and friendly error handling.
724 rpc = self._transport._wrapped_methods[self._transport.write_log_entries]
726 # Send the request.
727 response = rpc(
728 request,
729 retry=retry,
730 timeout=timeout,
731 metadata=metadata,
732 )
734 # Done; return the response.
735 return response
737 def list_log_entries(
738 self,
739 request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None,
740 *,
741 resource_names: Optional[MutableSequence[str]] = None,
742 filter: Optional[str] = None,
743 order_by: Optional[str] = None,
744 retry: OptionalRetry = gapic_v1.method.DEFAULT,
745 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
746 metadata: Sequence[Tuple[str, str]] = (),
747 ) -> pagers.ListLogEntriesPager:
748 r"""Lists log entries. Use this method to retrieve log entries that
749 originated from a project/folder/organization/billing account.
750 For ways to export log entries, see `Exporting
751 Logs <https://cloud.google.com/logging/docs/export>`__.
753 .. code-block:: python
755 # This snippet has been automatically generated and should be regarded as a
756 # code template only.
757 # It will require modifications to work:
758 # - It may require correct/in-range values for request initialization.
759 # - It may require specifying regional endpoints when creating the service
760 # client as shown in:
761 # https://googleapis.dev/python/google-api-core/latest/client_options.html
762 from google.cloud import logging_v2
764 def sample_list_log_entries():
765 # Create a client
766 client = logging_v2.LoggingServiceV2Client()
768 # Initialize request argument(s)
769 request = logging_v2.ListLogEntriesRequest(
770 resource_names=['resource_names_value1', 'resource_names_value2'],
771 )
773 # Make the request
774 page_result = client.list_log_entries(request=request)
776 # Handle the response
777 for response in page_result:
778 print(response)
780 Args:
781 request (Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]):
782 The request object. The parameters to ``ListLogEntries``.
783 resource_names (MutableSequence[str]):
784 Required. Names of one or more parent resources from
785 which to retrieve log entries:
787 - ``projects/[PROJECT_ID]``
788 - ``organizations/[ORGANIZATION_ID]``
789 - ``billingAccounts/[BILLING_ACCOUNT_ID]``
790 - ``folders/[FOLDER_ID]``
792 May alternatively be one or more views:
794 - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
795 - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
796 - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
797 - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]``
799 Projects listed in the ``project_ids`` field are added
800 to this list. A maximum of 100 resources may be
801 specified in a single request.
803 This corresponds to the ``resource_names`` field
804 on the ``request`` instance; if ``request`` is provided, this
805 should not be set.
806 filter (str):
807 Optional. Only log entries that match the filter are
808 returned. An empty filter matches all log entries in the
809 resources listed in ``resource_names``. Referencing a
810 parent resource that is not listed in ``resource_names``
811 will cause the filter to return no results. The maximum
812 length of a filter is 20,000 characters.
814 This corresponds to the ``filter`` field
815 on the ``request`` instance; if ``request`` is provided, this
816 should not be set.
817 order_by (str):
818 Optional. How the results should be sorted. Presently,
819 the only permitted values are ``"timestamp asc"``
820 (default) and ``"timestamp desc"``. The first option
821 returns entries in order of increasing values of
822 ``LogEntry.timestamp`` (oldest first), and the second
823 option returns entries in order of decreasing timestamps
824 (newest first). Entries with equal timestamps are
825 returned in order of their ``insert_id`` values.
827 This corresponds to the ``order_by`` field
828 on the ``request`` instance; if ``request`` is provided, this
829 should not be set.
830 retry (google.api_core.retry.Retry): Designation of what errors, if any,
831 should be retried.
832 timeout (float): The timeout for this request.
833 metadata (Sequence[Tuple[str, str]]): Strings which should be
834 sent along with the request as metadata.
836 Returns:
837 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesPager:
838 Result returned from ListLogEntries.
840 Iterating over this object will yield results and
841 resolve additional pages automatically.
843 """
844 # Create or coerce a protobuf request object.
845 # Quick check: If we got a request object, we should *not* have
846 # gotten any keyword arguments that map to the request.
847 has_flattened_params = any([resource_names, filter, order_by])
848 if request is not None and has_flattened_params:
849 raise ValueError(
850 "If the `request` argument is set, then none of "
851 "the individual field arguments should be set."
852 )
854 # Minor optimization to avoid making a copy if the user passes
855 # in a logging.ListLogEntriesRequest.
856 # There's no risk of modifying the input as we've already verified
857 # there are no flattened fields.
858 if not isinstance(request, logging.ListLogEntriesRequest):
859 request = logging.ListLogEntriesRequest(request)
860 # If we have keyword arguments corresponding to fields on the
861 # request, apply these.
862 if resource_names is not None:
863 request.resource_names = resource_names
864 if filter is not None:
865 request.filter = filter
866 if order_by is not None:
867 request.order_by = order_by
869 # Wrap the RPC method; this adds retry and timeout information,
870 # and friendly error handling.
871 rpc = self._transport._wrapped_methods[self._transport.list_log_entries]
873 # Send the request.
874 response = rpc(
875 request,
876 retry=retry,
877 timeout=timeout,
878 metadata=metadata,
879 )
881 # This method is paged; wrap the response in a pager, which provides
882 # an `__iter__` convenience method.
883 response = pagers.ListLogEntriesPager(
884 method=rpc,
885 request=request,
886 response=response,
887 metadata=metadata,
888 )
890 # Done; return the response.
891 return response
893 def list_monitored_resource_descriptors(
894 self,
895 request: Optional[
896 Union[logging.ListMonitoredResourceDescriptorsRequest, dict]
897 ] = None,
898 *,
899 retry: OptionalRetry = gapic_v1.method.DEFAULT,
900 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
901 metadata: Sequence[Tuple[str, str]] = (),
902 ) -> pagers.ListMonitoredResourceDescriptorsPager:
903 r"""Lists the descriptors for monitored resource types
904 used by Logging.
906 .. code-block:: python
908 # This snippet has been automatically generated and should be regarded as a
909 # code template only.
910 # It will require modifications to work:
911 # - It may require correct/in-range values for request initialization.
912 # - It may require specifying regional endpoints when creating the service
913 # client as shown in:
914 # https://googleapis.dev/python/google-api-core/latest/client_options.html
915 from google.cloud import logging_v2
917 def sample_list_monitored_resource_descriptors():
918 # Create a client
919 client = logging_v2.LoggingServiceV2Client()
921 # Initialize request argument(s)
922 request = logging_v2.ListMonitoredResourceDescriptorsRequest(
923 )
925 # Make the request
926 page_result = client.list_monitored_resource_descriptors(request=request)
928 # Handle the response
929 for response in page_result:
930 print(response)
932 Args:
933 request (Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]):
934 The request object. The parameters to
935 ListMonitoredResourceDescriptors
936 retry (google.api_core.retry.Retry): Designation of what errors, if any,
937 should be retried.
938 timeout (float): The timeout for this request.
939 metadata (Sequence[Tuple[str, str]]): Strings which should be
940 sent along with the request as metadata.
942 Returns:
943 google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsPager:
944 Result returned from
945 ListMonitoredResourceDescriptors.
946 Iterating over this object will yield
947 results and resolve additional pages
948 automatically.
950 """
951 # Create or coerce a protobuf request object.
952 # Minor optimization to avoid making a copy if the user passes
953 # in a logging.ListMonitoredResourceDescriptorsRequest.
954 # There's no risk of modifying the input as we've already verified
955 # there are no flattened fields.
956 if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest):
957 request = logging.ListMonitoredResourceDescriptorsRequest(request)
959 # Wrap the RPC method; this adds retry and timeout information,
960 # and friendly error handling.
961 rpc = self._transport._wrapped_methods[
962 self._transport.list_monitored_resource_descriptors
963 ]
965 # Send the request.
966 response = rpc(
967 request,
968 retry=retry,
969 timeout=timeout,
970 metadata=metadata,
971 )
973 # This method is paged; wrap the response in a pager, which provides
974 # an `__iter__` convenience method.
975 response = pagers.ListMonitoredResourceDescriptorsPager(
976 method=rpc,
977 request=request,
978 response=response,
979 metadata=metadata,
980 )
982 # Done; return the response.
983 return response
985 def list_logs(
986 self,
987 request: Optional[Union[logging.ListLogsRequest, dict]] = None,
988 *,
989 parent: Optional[str] = None,
990 retry: OptionalRetry = gapic_v1.method.DEFAULT,
991 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
992 metadata: Sequence[Tuple[str, str]] = (),
993 ) -> pagers.ListLogsPager:
994 r"""Lists the logs in projects, organizations, folders,
995 or billing accounts. Only logs that have entries are
996 listed.
998 .. code-block:: python
1000 # This snippet has been automatically generated and should be regarded as a
1001 # code template only.
1002 # It will require modifications to work:
1003 # - It may require correct/in-range values for request initialization.
1004 # - It may require specifying regional endpoints when creating the service
1005 # client as shown in:
1006 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1007 from google.cloud import logging_v2
1009 def sample_list_logs():
1010 # Create a client
1011 client = logging_v2.LoggingServiceV2Client()
1013 # Initialize request argument(s)
1014 request = logging_v2.ListLogsRequest(
1015 parent="parent_value",
1016 )
1018 # Make the request
1019 page_result = client.list_logs(request=request)
1021 # Handle the response
1022 for response in page_result:
1023 print(response)
1025 Args:
1026 request (Union[google.cloud.logging_v2.types.ListLogsRequest, dict]):
1027 The request object. The parameters to ListLogs.
1028 parent (str):
1029 Required. The resource name to list logs for:
1031 - ``projects/[PROJECT_ID]``
1032 - ``organizations/[ORGANIZATION_ID]``
1033 - ``billingAccounts/[BILLING_ACCOUNT_ID]``
1034 - ``folders/[FOLDER_ID]``
1036 This corresponds to the ``parent`` field
1037 on the ``request`` instance; if ``request`` is provided, this
1038 should not be set.
1039 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1040 should be retried.
1041 timeout (float): The timeout for this request.
1042 metadata (Sequence[Tuple[str, str]]): Strings which should be
1043 sent along with the request as metadata.
1045 Returns:
1046 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsPager:
1047 Result returned from ListLogs.
1049 Iterating over this object will yield
1050 results and resolve additional pages
1051 automatically.
1053 """
1054 # Create or coerce a protobuf request object.
1055 # Quick check: If we got a request object, we should *not* have
1056 # gotten any keyword arguments that map to the request.
1057 has_flattened_params = any([parent])
1058 if request is not None and has_flattened_params:
1059 raise ValueError(
1060 "If the `request` argument is set, then none of "
1061 "the individual field arguments should be set."
1062 )
1064 # Minor optimization to avoid making a copy if the user passes
1065 # in a logging.ListLogsRequest.
1066 # There's no risk of modifying the input as we've already verified
1067 # there are no flattened fields.
1068 if not isinstance(request, logging.ListLogsRequest):
1069 request = logging.ListLogsRequest(request)
1070 # If we have keyword arguments corresponding to fields on the
1071 # request, apply these.
1072 if parent is not None:
1073 request.parent = parent
1075 # Wrap the RPC method; this adds retry and timeout information,
1076 # and friendly error handling.
1077 rpc = self._transport._wrapped_methods[self._transport.list_logs]
1079 # Certain fields should be provided within the metadata header;
1080 # add these here.
1081 metadata = tuple(metadata) + (
1082 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1083 )
1085 # Send the request.
1086 response = rpc(
1087 request,
1088 retry=retry,
1089 timeout=timeout,
1090 metadata=metadata,
1091 )
1093 # This method is paged; wrap the response in a pager, which provides
1094 # an `__iter__` convenience method.
1095 response = pagers.ListLogsPager(
1096 method=rpc,
1097 request=request,
1098 response=response,
1099 metadata=metadata,
1100 )
1102 # Done; return the response.
1103 return response
1105 def tail_log_entries(
1106 self,
1107 requests: Optional[Iterator[logging.TailLogEntriesRequest]] = None,
1108 *,
1109 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1110 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1111 metadata: Sequence[Tuple[str, str]] = (),
1112 ) -> Iterable[logging.TailLogEntriesResponse]:
1113 r"""Streaming read of log entries as they are ingested.
1114 Until the stream is terminated, it will continue reading
1115 logs.
1117 .. code-block:: python
1119 # This snippet has been automatically generated and should be regarded as a
1120 # code template only.
1121 # It will require modifications to work:
1122 # - It may require correct/in-range values for request initialization.
1123 # - It may require specifying regional endpoints when creating the service
1124 # client as shown in:
1125 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1126 from google.cloud import logging_v2
1128 def sample_tail_log_entries():
1129 # Create a client
1130 client = logging_v2.LoggingServiceV2Client()
1132 # Initialize request argument(s)
1133 request = logging_v2.TailLogEntriesRequest(
1134 resource_names=['resource_names_value1', 'resource_names_value2'],
1135 )
1137 # This method expects an iterator which contains
1138 # 'logging_v2.TailLogEntriesRequest' objects
1139 # Here we create a generator that yields a single `request` for
1140 # demonstrative purposes.
1141 requests = [request]
1143 def request_generator():
1144 for request in requests:
1145 yield request
1147 # Make the request
1148 stream = client.tail_log_entries(requests=request_generator())
1150 # Handle the response
1151 for response in stream:
1152 print(response)
1154 Args:
1155 requests (Iterator[google.cloud.logging_v2.types.TailLogEntriesRequest]):
1156 The request object iterator. The parameters to ``TailLogEntries``.
1157 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1158 should be retried.
1159 timeout (float): The timeout for this request.
1160 metadata (Sequence[Tuple[str, str]]): Strings which should be
1161 sent along with the request as metadata.
1163 Returns:
1164 Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]:
1165 Result returned from TailLogEntries.
1166 """
1168 # Wrap the RPC method; this adds retry and timeout information,
1169 # and friendly error handling.
1170 rpc = self._transport._wrapped_methods[self._transport.tail_log_entries]
1172 # Send the request.
1173 response = rpc(
1174 requests,
1175 retry=retry,
1176 timeout=timeout,
1177 metadata=metadata,
1178 )
1180 # Done; return the response.
1181 return response
1183 def __enter__(self) -> "LoggingServiceV2Client":
1184 return self
1186 def __exit__(self, type, value, traceback):
1187 """Releases underlying transport's resources.
1189 .. warning::
1190 ONLY use as a context manager if the transport is NOT shared
1191 with other clients! Exiting the with block will CLOSE the transport
1192 and may cause errors in other clients!
1193 """
1194 self.transport.close()
1196 def list_operations(
1197 self,
1198 request: Optional[operations_pb2.ListOperationsRequest] = None,
1199 *,
1200 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1201 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1202 metadata: Sequence[Tuple[str, str]] = (),
1203 ) -> operations_pb2.ListOperationsResponse:
1204 r"""Lists operations that match the specified filter in the request.
1206 Args:
1207 request (:class:`~.operations_pb2.ListOperationsRequest`):
1208 The request object. Request message for
1209 `ListOperations` method.
1210 retry (google.api_core.retry.Retry): Designation of what errors,
1211 if any, should be retried.
1212 timeout (float): The timeout for this request.
1213 metadata (Sequence[Tuple[str, str]]): Strings which should be
1214 sent along with the request as metadata.
1215 Returns:
1216 ~.operations_pb2.ListOperationsResponse:
1217 Response message for ``ListOperations`` method.
1218 """
1219 # Create or coerce a protobuf request object.
1220 # The request isn't a proto-plus wrapped type,
1221 # so it must be constructed via keyword expansion.
1222 if isinstance(request, dict):
1223 request = operations_pb2.ListOperationsRequest(**request)
1225 # Wrap the RPC method; this adds retry and timeout information,
1226 # and friendly error handling.
1227 rpc = gapic_v1.method.wrap_method(
1228 self._transport.list_operations,
1229 default_timeout=None,
1230 client_info=DEFAULT_CLIENT_INFO,
1231 )
1233 # Certain fields should be provided within the metadata header;
1234 # add these here.
1235 metadata = tuple(metadata) + (
1236 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1237 )
1239 # Send the request.
1240 response = rpc(
1241 request,
1242 retry=retry,
1243 timeout=timeout,
1244 metadata=metadata,
1245 )
1247 # Done; return the response.
1248 return response
1250 def get_operation(
1251 self,
1252 request: Optional[operations_pb2.GetOperationRequest] = None,
1253 *,
1254 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1255 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1256 metadata: Sequence[Tuple[str, str]] = (),
1257 ) -> operations_pb2.Operation:
1258 r"""Gets the latest state of a long-running operation.
1260 Args:
1261 request (:class:`~.operations_pb2.GetOperationRequest`):
1262 The request object. Request message for
1263 `GetOperation` method.
1264 retry (google.api_core.retry.Retry): Designation of what errors,
1265 if any, should be retried.
1266 timeout (float): The timeout for this request.
1267 metadata (Sequence[Tuple[str, str]]): Strings which should be
1268 sent along with the request as metadata.
1269 Returns:
1270 ~.operations_pb2.Operation:
1271 An ``Operation`` object.
1272 """
1273 # Create or coerce a protobuf request object.
1274 # The request isn't a proto-plus wrapped type,
1275 # so it must be constructed via keyword expansion.
1276 if isinstance(request, dict):
1277 request = operations_pb2.GetOperationRequest(**request)
1279 # Wrap the RPC method; this adds retry and timeout information,
1280 # and friendly error handling.
1281 rpc = gapic_v1.method.wrap_method(
1282 self._transport.get_operation,
1283 default_timeout=None,
1284 client_info=DEFAULT_CLIENT_INFO,
1285 )
1287 # Certain fields should be provided within the metadata header;
1288 # add these here.
1289 metadata = tuple(metadata) + (
1290 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1291 )
1293 # Send the request.
1294 response = rpc(
1295 request,
1296 retry=retry,
1297 timeout=timeout,
1298 metadata=metadata,
1299 )
1301 # Done; return the response.
1302 return response
1304 def cancel_operation(
1305 self,
1306 request: Optional[operations_pb2.CancelOperationRequest] = None,
1307 *,
1308 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1309 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1310 metadata: Sequence[Tuple[str, str]] = (),
1311 ) -> None:
1312 r"""Starts asynchronous cancellation on a long-running operation.
1314 The server makes a best effort to cancel the operation, but success
1315 is not guaranteed. If the server doesn't support this method, it returns
1316 `google.rpc.Code.UNIMPLEMENTED`.
1318 Args:
1319 request (:class:`~.operations_pb2.CancelOperationRequest`):
1320 The request object. Request message for
1321 `CancelOperation` method.
1322 retry (google.api_core.retry.Retry): Designation of what errors,
1323 if any, should be retried.
1324 timeout (float): The timeout for this request.
1325 metadata (Sequence[Tuple[str, str]]): Strings which should be
1326 sent along with the request as metadata.
1327 Returns:
1328 None
1329 """
1330 # Create or coerce a protobuf request object.
1331 # The request isn't a proto-plus wrapped type,
1332 # so it must be constructed via keyword expansion.
1333 if isinstance(request, dict):
1334 request = operations_pb2.CancelOperationRequest(**request)
1336 # Wrap the RPC method; this adds retry and timeout information,
1337 # and friendly error handling.
1338 rpc = gapic_v1.method.wrap_method(
1339 self._transport.cancel_operation,
1340 default_timeout=None,
1341 client_info=DEFAULT_CLIENT_INFO,
1342 )
1344 # Certain fields should be provided within the metadata header;
1345 # add these here.
1346 metadata = tuple(metadata) + (
1347 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1348 )
1350 # Send the request.
1351 rpc(
1352 request,
1353 retry=retry,
1354 timeout=timeout,
1355 metadata=metadata,
1356 )
1359DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1360 gapic_version=package_version.__version__
1361)
1364__all__ = ("LoggingServiceV2Client",)