Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/cloud/logging_v2/services/logging_service_v2/client.py: 38%

219 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-26 07:30 +0000

1# -*- coding: utf-8 -*- 

2# Copyright 2022 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) 

33 

34from google.cloud.logging_v2 import gapic_version as package_version 

35 

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 

45 

46try: 

47 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] 

48except AttributeError: # pragma: NO COVER 

49 OptionalRetry = Union[retries.Retry, object] # type: ignore 

50 

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 .transports.base import LoggingServiceV2Transport, DEFAULT_CLIENT_INFO 

56from .transports.grpc import LoggingServiceV2GrpcTransport 

57from .transports.grpc_asyncio import LoggingServiceV2GrpcAsyncIOTransport 

58 

59 

60class LoggingServiceV2ClientMeta(type): 

61 """Metaclass for the LoggingServiceV2 client. 

62 

63 This provides class-level methods for building and retrieving 

64 support objects (e.g. transport) without polluting the client instance 

65 objects. 

66 """ 

67 

68 _transport_registry = ( 

69 OrderedDict() 

70 ) # type: Dict[str, Type[LoggingServiceV2Transport]] 

71 _transport_registry["grpc"] = LoggingServiceV2GrpcTransport 

72 _transport_registry["grpc_asyncio"] = LoggingServiceV2GrpcAsyncIOTransport 

73 

74 def get_transport_class( 

75 cls, 

76 label: Optional[str] = None, 

77 ) -> Type[LoggingServiceV2Transport]: 

78 """Returns an appropriate transport class. 

79 

80 Args: 

81 label: The name of the desired transport. If none is 

82 provided, then the first transport in the registry is used. 

83 

84 Returns: 

85 The transport class to use. 

86 """ 

87 # If a specific transport is requested, return that one. 

88 if label: 

89 return cls._transport_registry[label] 

90 

91 # No transport is requested; return the default (that is, the first one 

92 # in the dictionary). 

93 return next(iter(cls._transport_registry.values())) 

94 

95 

96class LoggingServiceV2Client(metaclass=LoggingServiceV2ClientMeta): 

97 """Service for ingesting and querying logs.""" 

98 

99 @staticmethod 

100 def _get_default_mtls_endpoint(api_endpoint): 

101 """Converts api endpoint to mTLS endpoint. 

102 

103 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to 

104 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. 

105 Args: 

106 api_endpoint (Optional[str]): the api endpoint to convert. 

107 Returns: 

108 str: converted mTLS api endpoint. 

109 """ 

110 if not api_endpoint: 

111 return api_endpoint 

112 

113 mtls_endpoint_re = re.compile( 

114 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" 

115 ) 

116 

117 m = mtls_endpoint_re.match(api_endpoint) 

118 name, mtls, sandbox, googledomain = m.groups() 

119 if mtls or not googledomain: 

120 return api_endpoint 

121 

122 if sandbox: 

123 return api_endpoint.replace( 

124 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

125 ) 

126 

127 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") 

128 

129 DEFAULT_ENDPOINT = "logging.googleapis.com" 

130 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

131 DEFAULT_ENDPOINT 

132 ) 

133 

134 @classmethod 

135 def from_service_account_info(cls, info: dict, *args, **kwargs): 

136 """Creates an instance of this client using the provided credentials 

137 info. 

138 

139 Args: 

140 info (dict): The service account private key info. 

141 args: Additional arguments to pass to the constructor. 

142 kwargs: Additional arguments to pass to the constructor. 

143 

144 Returns: 

145 LoggingServiceV2Client: The constructed client. 

146 """ 

147 credentials = service_account.Credentials.from_service_account_info(info) 

148 kwargs["credentials"] = credentials 

149 return cls(*args, **kwargs) 

150 

151 @classmethod 

152 def from_service_account_file(cls, filename: str, *args, **kwargs): 

153 """Creates an instance of this client using the provided credentials 

154 file. 

155 

156 Args: 

157 filename (str): The path to the service account private key json 

158 file. 

159 args: Additional arguments to pass to the constructor. 

160 kwargs: Additional arguments to pass to the constructor. 

161 

162 Returns: 

163 LoggingServiceV2Client: The constructed client. 

164 """ 

165 credentials = service_account.Credentials.from_service_account_file(filename) 

166 kwargs["credentials"] = credentials 

167 return cls(*args, **kwargs) 

168 

169 from_service_account_json = from_service_account_file 

170 

171 @property 

172 def transport(self) -> LoggingServiceV2Transport: 

173 """Returns the transport used by the client instance. 

174 

175 Returns: 

176 LoggingServiceV2Transport: The transport used by the client 

177 instance. 

178 """ 

179 return self._transport 

180 

181 @staticmethod 

182 def log_path( 

183 project: str, 

184 log: str, 

185 ) -> str: 

186 """Returns a fully-qualified log string.""" 

187 return "projects/{project}/logs/{log}".format( 

188 project=project, 

189 log=log, 

190 ) 

191 

192 @staticmethod 

193 def parse_log_path(path: str) -> Dict[str, str]: 

194 """Parses a log path into its component segments.""" 

195 m = re.match(r"^projects/(?P<project>.+?)/logs/(?P<log>.+?)$", path) 

196 return m.groupdict() if m else {} 

197 

198 @staticmethod 

199 def common_billing_account_path( 

200 billing_account: str, 

201 ) -> str: 

202 """Returns a fully-qualified billing_account string.""" 

203 return "billingAccounts/{billing_account}".format( 

204 billing_account=billing_account, 

205 ) 

206 

207 @staticmethod 

208 def parse_common_billing_account_path(path: str) -> Dict[str, str]: 

209 """Parse a billing_account path into its component segments.""" 

210 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) 

211 return m.groupdict() if m else {} 

212 

213 @staticmethod 

214 def common_folder_path( 

215 folder: str, 

216 ) -> str: 

217 """Returns a fully-qualified folder string.""" 

218 return "folders/{folder}".format( 

219 folder=folder, 

220 ) 

221 

222 @staticmethod 

223 def parse_common_folder_path(path: str) -> Dict[str, str]: 

224 """Parse a folder path into its component segments.""" 

225 m = re.match(r"^folders/(?P<folder>.+?)$", path) 

226 return m.groupdict() if m else {} 

227 

228 @staticmethod 

229 def common_organization_path( 

230 organization: str, 

231 ) -> str: 

232 """Returns a fully-qualified organization string.""" 

233 return "organizations/{organization}".format( 

234 organization=organization, 

235 ) 

236 

237 @staticmethod 

238 def parse_common_organization_path(path: str) -> Dict[str, str]: 

239 """Parse a organization path into its component segments.""" 

240 m = re.match(r"^organizations/(?P<organization>.+?)$", path) 

241 return m.groupdict() if m else {} 

242 

243 @staticmethod 

244 def common_project_path( 

245 project: str, 

246 ) -> str: 

247 """Returns a fully-qualified project string.""" 

248 return "projects/{project}".format( 

249 project=project, 

250 ) 

251 

252 @staticmethod 

253 def parse_common_project_path(path: str) -> Dict[str, str]: 

254 """Parse a project path into its component segments.""" 

255 m = re.match(r"^projects/(?P<project>.+?)$", path) 

256 return m.groupdict() if m else {} 

257 

258 @staticmethod 

259 def common_location_path( 

260 project: str, 

261 location: str, 

262 ) -> str: 

263 """Returns a fully-qualified location string.""" 

264 return "projects/{project}/locations/{location}".format( 

265 project=project, 

266 location=location, 

267 ) 

268 

269 @staticmethod 

270 def parse_common_location_path(path: str) -> Dict[str, str]: 

271 """Parse a location path into its component segments.""" 

272 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) 

273 return m.groupdict() if m else {} 

274 

275 @classmethod 

276 def get_mtls_endpoint_and_cert_source( 

277 cls, client_options: Optional[client_options_lib.ClientOptions] = None 

278 ): 

279 """Return the API endpoint and client cert source for mutual TLS. 

280 

281 The client cert source is determined in the following order: 

282 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

283 client cert source is None. 

284 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

285 default client cert source exists, use the default one; otherwise the client cert 

286 source is None. 

287 

288 The API endpoint is determined in the following order: 

289 (1) if `client_options.api_endpoint` if provided, use the provided one. 

290 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

291 default mTLS endpoint; if the environment variable is "never", use the default API 

292 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

293 use the default API endpoint. 

294 

295 More details can be found at https://google.aip.dev/auth/4114. 

296 

297 Args: 

298 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

299 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

300 in this method. 

301 

302 Returns: 

303 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

304 client cert source to use. 

305 

306 Raises: 

307 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

308 """ 

309 if client_options is None: 

310 client_options = client_options_lib.ClientOptions() 

311 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") 

312 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") 

313 if use_client_cert not in ("true", "false"): 

314 raise ValueError( 

315 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

316 ) 

317 if use_mtls_endpoint not in ("auto", "never", "always"): 

318 raise MutualTLSChannelError( 

319 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

320 ) 

321 

322 # Figure out the client cert source to use. 

323 client_cert_source = None 

324 if use_client_cert == "true": 

325 if client_options.client_cert_source: 

326 client_cert_source = client_options.client_cert_source 

327 elif mtls.has_default_client_cert_source(): 

328 client_cert_source = mtls.default_client_cert_source() 

329 

330 # Figure out which api endpoint to use. 

331 if client_options.api_endpoint is not None: 

332 api_endpoint = client_options.api_endpoint 

333 elif use_mtls_endpoint == "always" or ( 

334 use_mtls_endpoint == "auto" and client_cert_source 

335 ): 

336 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

337 else: 

338 api_endpoint = cls.DEFAULT_ENDPOINT 

339 

340 return api_endpoint, client_cert_source 

341 

342 def __init__( 

343 self, 

344 *, 

345 credentials: Optional[ga_credentials.Credentials] = None, 

346 transport: Optional[Union[str, LoggingServiceV2Transport]] = None, 

347 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, 

348 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

349 ) -> None: 

350 """Instantiates the logging service v2 client. 

351 

352 Args: 

353 credentials (Optional[google.auth.credentials.Credentials]): The 

354 authorization credentials to attach to requests. These 

355 credentials identify the application to the service; if none 

356 are specified, the client will attempt to ascertain the 

357 credentials from the environment. 

358 transport (Union[str, LoggingServiceV2Transport]): The 

359 transport to use. If set to None, a transport is chosen 

360 automatically. 

361 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the 

362 client. It won't take effect if a ``transport`` instance is provided. 

363 (1) The ``api_endpoint`` property can be used to override the 

364 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT 

365 environment variable can also be used to override the endpoint: 

366 "always" (always use the default mTLS endpoint), "never" (always 

367 use the default regular endpoint) and "auto" (auto switch to the 

368 default mTLS endpoint if client certificate is present, this is 

369 the default value). However, the ``api_endpoint`` property takes 

370 precedence if provided. 

371 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

372 is "true", then the ``client_cert_source`` property can be used 

373 to provide client certificate for mutual TLS transport. If 

374 not provided, the default SSL client certificate will be used if 

375 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

376 set, no client certificate will be used. 

377 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

378 The client info used to send a user-agent string along with 

379 API requests. If ``None``, then default info will be used. 

380 Generally, you only need to set this if you're developing 

381 your own client library. 

382 

383 Raises: 

384 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport 

385 creation failed for any reason. 

386 """ 

387 if isinstance(client_options, dict): 

388 client_options = client_options_lib.from_dict(client_options) 

389 if client_options is None: 

390 client_options = client_options_lib.ClientOptions() 

391 client_options = cast(client_options_lib.ClientOptions, client_options) 

392 

393 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( 

394 client_options 

395 ) 

396 

397 api_key_value = getattr(client_options, "api_key", None) 

398 if api_key_value and credentials: 

399 raise ValueError( 

400 "client_options.api_key and credentials are mutually exclusive" 

401 ) 

402 

403 # Save or instantiate the transport. 

404 # Ordinarily, we provide the transport, but allowing a custom transport 

405 # instance provides an extensibility point for unusual situations. 

406 if isinstance(transport, LoggingServiceV2Transport): 

407 # transport is a LoggingServiceV2Transport instance. 

408 if credentials or client_options.credentials_file or api_key_value: 

409 raise ValueError( 

410 "When providing a transport instance, " 

411 "provide its credentials directly." 

412 ) 

413 if client_options.scopes: 

414 raise ValueError( 

415 "When providing a transport instance, provide its scopes " 

416 "directly." 

417 ) 

418 self._transport = transport 

419 else: 

420 import google.auth._default # type: ignore 

421 

422 if api_key_value and hasattr( 

423 google.auth._default, "get_api_key_credentials" 

424 ): 

425 credentials = google.auth._default.get_api_key_credentials( 

426 api_key_value 

427 ) 

428 

429 Transport = type(self).get_transport_class(transport) 

430 self._transport = Transport( 

431 credentials=credentials, 

432 credentials_file=client_options.credentials_file, 

433 host=api_endpoint, 

434 scopes=client_options.scopes, 

435 client_cert_source_for_mtls=client_cert_source_func, 

436 quota_project_id=client_options.quota_project_id, 

437 client_info=client_info, 

438 always_use_jwt_access=True, 

439 api_audience=client_options.api_audience, 

440 ) 

441 

442 def delete_log( 

443 self, 

444 request: Optional[Union[logging.DeleteLogRequest, dict]] = None, 

445 *, 

446 log_name: Optional[str] = None, 

447 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

448 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

449 metadata: Sequence[Tuple[str, str]] = (), 

450 ) -> None: 

451 r"""Deletes all the log entries in a log for the \_Default Log 

452 Bucket. The log reappears if it receives new entries. Log 

453 entries written shortly before the delete operation might not be 

454 deleted. Entries received after the delete operation with a 

455 timestamp before the operation will be deleted. 

456 

457 .. code-block:: python 

458 

459 # This snippet has been automatically generated and should be regarded as a 

460 # code template only. 

461 # It will require modifications to work: 

462 # - It may require correct/in-range values for request initialization. 

463 # - It may require specifying regional endpoints when creating the service 

464 # client as shown in: 

465 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

466 from google.cloud import logging_v2 

467 

468 def sample_delete_log(): 

469 # Create a client 

470 client = logging_v2.LoggingServiceV2Client() 

471 

472 # Initialize request argument(s) 

473 request = logging_v2.DeleteLogRequest( 

474 log_name="log_name_value", 

475 ) 

476 

477 # Make the request 

478 client.delete_log(request=request) 

479 

480 Args: 

481 request (Union[google.cloud.logging_v2.types.DeleteLogRequest, dict]): 

482 The request object. The parameters to DeleteLog. 

483 log_name (str): 

484 Required. The resource name of the log to delete: 

485 

486 - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` 

487 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` 

488 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` 

489 - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` 

490 

491 ``[LOG_ID]`` must be URL-encoded. For example, 

492 ``"projects/my-project-id/logs/syslog"``, 

493 ``"organizations/123/logs/cloudaudit.googleapis.com%2Factivity"``. 

494 

495 For more information about log names, see 

496 [LogEntry][google.logging.v2.LogEntry]. 

497 

498 This corresponds to the ``log_name`` field 

499 on the ``request`` instance; if ``request`` is provided, this 

500 should not be set. 

501 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

502 should be retried. 

503 timeout (float): The timeout for this request. 

504 metadata (Sequence[Tuple[str, str]]): Strings which should be 

505 sent along with the request as metadata. 

506 """ 

507 # Create or coerce a protobuf request object. 

508 # Quick check: If we got a request object, we should *not* have 

509 # gotten any keyword arguments that map to the request. 

510 has_flattened_params = any([log_name]) 

511 if request is not None and has_flattened_params: 

512 raise ValueError( 

513 "If the `request` argument is set, then none of " 

514 "the individual field arguments should be set." 

515 ) 

516 

517 # Minor optimization to avoid making a copy if the user passes 

518 # in a logging.DeleteLogRequest. 

519 # There's no risk of modifying the input as we've already verified 

520 # there are no flattened fields. 

521 if not isinstance(request, logging.DeleteLogRequest): 

522 request = logging.DeleteLogRequest(request) 

523 # If we have keyword arguments corresponding to fields on the 

524 # request, apply these. 

525 if log_name is not None: 

526 request.log_name = log_name 

527 

528 # Wrap the RPC method; this adds retry and timeout information, 

529 # and friendly error handling. 

530 rpc = self._transport._wrapped_methods[self._transport.delete_log] 

531 

532 # Certain fields should be provided within the metadata header; 

533 # add these here. 

534 metadata = tuple(metadata) + ( 

535 gapic_v1.routing_header.to_grpc_metadata((("log_name", request.log_name),)), 

536 ) 

537 

538 # Send the request. 

539 rpc( 

540 request, 

541 retry=retry, 

542 timeout=timeout, 

543 metadata=metadata, 

544 ) 

545 

546 def write_log_entries( 

547 self, 

548 request: Optional[Union[logging.WriteLogEntriesRequest, dict]] = None, 

549 *, 

550 log_name: Optional[str] = None, 

551 resource: Optional[monitored_resource_pb2.MonitoredResource] = None, 

552 labels: Optional[MutableMapping[str, str]] = None, 

553 entries: Optional[MutableSequence[log_entry.LogEntry]] = None, 

554 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

555 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

556 metadata: Sequence[Tuple[str, str]] = (), 

557 ) -> logging.WriteLogEntriesResponse: 

558 r"""Writes log entries to Logging. This API method is the 

559 only way to send log entries to Logging. This method is 

560 used, directly or indirectly, by the Logging agent 

561 (fluentd) and all logging libraries configured to use 

562 Logging. A single request may contain log entries for a 

563 maximum of 1000 different resources (projects, 

564 organizations, billing accounts or folders) 

565 

566 .. code-block:: python 

567 

568 # This snippet has been automatically generated and should be regarded as a 

569 # code template only. 

570 # It will require modifications to work: 

571 # - It may require correct/in-range values for request initialization. 

572 # - It may require specifying regional endpoints when creating the service 

573 # client as shown in: 

574 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

575 from google.cloud import logging_v2 

576 

577 def sample_write_log_entries(): 

578 # Create a client 

579 client = logging_v2.LoggingServiceV2Client() 

580 

581 # Initialize request argument(s) 

582 entries = logging_v2.LogEntry() 

583 entries.log_name = "log_name_value" 

584 

585 request = logging_v2.WriteLogEntriesRequest( 

586 entries=entries, 

587 ) 

588 

589 # Make the request 

590 response = client.write_log_entries(request=request) 

591 

592 # Handle the response 

593 print(response) 

594 

595 Args: 

596 request (Union[google.cloud.logging_v2.types.WriteLogEntriesRequest, dict]): 

597 The request object. The parameters to WriteLogEntries. 

598 log_name (str): 

599 Optional. A default log resource name that is assigned 

600 to all log entries in ``entries`` that do not specify a 

601 value for ``log_name``: 

602 

603 - ``projects/[PROJECT_ID]/logs/[LOG_ID]`` 

604 - ``organizations/[ORGANIZATION_ID]/logs/[LOG_ID]`` 

605 - ``billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]`` 

606 - ``folders/[FOLDER_ID]/logs/[LOG_ID]`` 

607 

608 ``[LOG_ID]`` must be URL-encoded. For example: 

609 

610 :: 

611 

612 "projects/my-project-id/logs/syslog" 

613 "organizations/123/logs/cloudaudit.googleapis.com%2Factivity" 

614 

615 The permission ``logging.logEntries.create`` is needed 

616 on each project, organization, billing account, or 

617 folder that is receiving new log entries, whether the 

618 resource is specified in ``logName`` or in an individual 

619 log entry. 

620 

621 This corresponds to the ``log_name`` field 

622 on the ``request`` instance; if ``request`` is provided, this 

623 should not be set. 

624 resource (google.api.monitored_resource_pb2.MonitoredResource): 

625 Optional. A default monitored resource object that is 

626 assigned to all log entries in ``entries`` that do not 

627 specify a value for ``resource``. Example: 

628 

629 :: 

630 

631 { "type": "gce_instance", 

632 "labels": { 

633 "zone": "us-central1-a", "instance_id": "00000000000000000000" }} 

634 

635 See [LogEntry][google.logging.v2.LogEntry]. 

636 

637 This corresponds to the ``resource`` field 

638 on the ``request`` instance; if ``request`` is provided, this 

639 should not be set. 

640 labels (MutableMapping[str, str]): 

641 Optional. Default labels that are added to the 

642 ``labels`` field of all log entries in ``entries``. If a 

643 log entry already has a label with the same key as a 

644 label in this parameter, then the log entry's label is 

645 not changed. See [LogEntry][google.logging.v2.LogEntry]. 

646 

647 This corresponds to the ``labels`` field 

648 on the ``request`` instance; if ``request`` is provided, this 

649 should not be set. 

650 entries (MutableSequence[google.cloud.logging_v2.types.LogEntry]): 

651 Required. The log entries to send to Logging. The order 

652 of log entries in this list does not matter. Values 

653 supplied in this method's ``log_name``, ``resource``, 

654 and ``labels`` fields are copied into those log entries 

655 in this list that do not include values for their 

656 corresponding fields. For more information, see the 

657 [LogEntry][google.logging.v2.LogEntry] type. 

658 

659 If the ``timestamp`` or ``insert_id`` fields are missing 

660 in log entries, then this method supplies the current 

661 time or a unique identifier, respectively. The supplied 

662 values are chosen so that, among the log entries that 

663 did not supply their own values, the entries earlier in 

664 the list will sort before the entries later in the list. 

665 See the ``entries.list`` method. 

666 

667 Log entries with timestamps that are more than the `logs 

668 retention 

669 period <https://cloud.google.com/logging/quotas>`__ in 

670 the past or more than 24 hours in the future will not be 

671 available when calling ``entries.list``. However, those 

672 log entries can still be `exported with 

673 LogSinks <https://cloud.google.com/logging/docs/api/tasks/exporting-logs>`__. 

674 

675 To improve throughput and to avoid exceeding the `quota 

676 limit <https://cloud.google.com/logging/quotas>`__ for 

677 calls to ``entries.write``, you should try to include 

678 several log entries in this list, rather than calling 

679 this method for each individual log entry. 

680 

681 This corresponds to the ``entries`` field 

682 on the ``request`` instance; if ``request`` is provided, this 

683 should not be set. 

684 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

685 should be retried. 

686 timeout (float): The timeout for this request. 

687 metadata (Sequence[Tuple[str, str]]): Strings which should be 

688 sent along with the request as metadata. 

689 

690 Returns: 

691 google.cloud.logging_v2.types.WriteLogEntriesResponse: 

692 Result returned from WriteLogEntries. 

693 """ 

694 # Create or coerce a protobuf request object. 

695 # Quick check: If we got a request object, we should *not* have 

696 # gotten any keyword arguments that map to the request. 

697 has_flattened_params = any([log_name, resource, labels, entries]) 

698 if request is not None and has_flattened_params: 

699 raise ValueError( 

700 "If the `request` argument is set, then none of " 

701 "the individual field arguments should be set." 

702 ) 

703 

704 # Minor optimization to avoid making a copy if the user passes 

705 # in a logging.WriteLogEntriesRequest. 

706 # There's no risk of modifying the input as we've already verified 

707 # there are no flattened fields. 

708 if not isinstance(request, logging.WriteLogEntriesRequest): 

709 request = logging.WriteLogEntriesRequest(request) 

710 # If we have keyword arguments corresponding to fields on the 

711 # request, apply these. 

712 if log_name is not None: 

713 request.log_name = log_name 

714 if resource is not None: 

715 request.resource = resource 

716 if labels is not None: 

717 request.labels = labels 

718 if entries is not None: 

719 request.entries = entries 

720 

721 # Wrap the RPC method; this adds retry and timeout information, 

722 # and friendly error handling. 

723 rpc = self._transport._wrapped_methods[self._transport.write_log_entries] 

724 

725 # Send the request. 

726 response = rpc( 

727 request, 

728 retry=retry, 

729 timeout=timeout, 

730 metadata=metadata, 

731 ) 

732 

733 # Done; return the response. 

734 return response 

735 

736 def list_log_entries( 

737 self, 

738 request: Optional[Union[logging.ListLogEntriesRequest, dict]] = None, 

739 *, 

740 resource_names: Optional[MutableSequence[str]] = None, 

741 filter: Optional[str] = None, 

742 order_by: Optional[str] = None, 

743 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

744 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

745 metadata: Sequence[Tuple[str, str]] = (), 

746 ) -> pagers.ListLogEntriesPager: 

747 r"""Lists log entries. Use this method to retrieve log entries that 

748 originated from a project/folder/organization/billing account. 

749 For ways to export log entries, see `Exporting 

750 Logs <https://cloud.google.com/logging/docs/export>`__. 

751 

752 .. code-block:: python 

753 

754 # This snippet has been automatically generated and should be regarded as a 

755 # code template only. 

756 # It will require modifications to work: 

757 # - It may require correct/in-range values for request initialization. 

758 # - It may require specifying regional endpoints when creating the service 

759 # client as shown in: 

760 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

761 from google.cloud import logging_v2 

762 

763 def sample_list_log_entries(): 

764 # Create a client 

765 client = logging_v2.LoggingServiceV2Client() 

766 

767 # Initialize request argument(s) 

768 request = logging_v2.ListLogEntriesRequest( 

769 resource_names=['resource_names_value1', 'resource_names_value2'], 

770 ) 

771 

772 # Make the request 

773 page_result = client.list_log_entries(request=request) 

774 

775 # Handle the response 

776 for response in page_result: 

777 print(response) 

778 

779 Args: 

780 request (Union[google.cloud.logging_v2.types.ListLogEntriesRequest, dict]): 

781 The request object. The parameters to `ListLogEntries`. 

782 resource_names (MutableSequence[str]): 

783 Required. Names of one or more parent resources from 

784 which to retrieve log entries: 

785 

786 - ``projects/[PROJECT_ID]`` 

787 - ``organizations/[ORGANIZATION_ID]`` 

788 - ``billingAccounts/[BILLING_ACCOUNT_ID]`` 

789 - ``folders/[FOLDER_ID]`` 

790 

791 May alternatively be one or more views: 

792 

793 - ``projects/[PROJECT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` 

794 - ``organizations/[ORGANIZATION_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` 

795 - ``billingAccounts/[BILLING_ACCOUNT_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` 

796 - ``folders/[FOLDER_ID]/locations/[LOCATION_ID]/buckets/[BUCKET_ID]/views/[VIEW_ID]`` 

797 

798 Projects listed in the ``project_ids`` field are added 

799 to this list. 

800 

801 This corresponds to the ``resource_names`` field 

802 on the ``request`` instance; if ``request`` is provided, this 

803 should not be set. 

804 filter (str): 

805 Optional. A filter that chooses which log entries to 

806 return. See `Advanced Logs 

807 Queries <https://cloud.google.com/logging/docs/view/advanced-queries>`__. 

808 Only log entries that match the filter are returned. An 

809 empty filter matches all log entries in the resources 

810 listed in ``resource_names``. Referencing a parent 

811 resource that is not listed in ``resource_names`` will 

812 cause the filter to return no results. The maximum 

813 length of the filter is 20000 characters. 

814 

815 This corresponds to the ``filter`` field 

816 on the ``request`` instance; if ``request`` is provided, this 

817 should not be set. 

818 order_by (str): 

819 Optional. How the results should be sorted. Presently, 

820 the only permitted values are ``"timestamp asc"`` 

821 (default) and ``"timestamp desc"``. The first option 

822 returns entries in order of increasing values of 

823 ``LogEntry.timestamp`` (oldest first), and the second 

824 option returns entries in order of decreasing timestamps 

825 (newest first). Entries with equal timestamps are 

826 returned in order of their ``insert_id`` values. 

827 

828 This corresponds to the ``order_by`` field 

829 on the ``request`` instance; if ``request`` is provided, this 

830 should not be set. 

831 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

832 should be retried. 

833 timeout (float): The timeout for this request. 

834 metadata (Sequence[Tuple[str, str]]): Strings which should be 

835 sent along with the request as metadata. 

836 

837 Returns: 

838 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogEntriesPager: 

839 Result returned from ListLogEntries. 

840 

841 Iterating over this object will yield results and 

842 resolve additional pages automatically. 

843 

844 """ 

845 # Create or coerce a protobuf request object. 

846 # Quick check: If we got a request object, we should *not* have 

847 # gotten any keyword arguments that map to the request. 

848 has_flattened_params = any([resource_names, filter, order_by]) 

849 if request is not None and has_flattened_params: 

850 raise ValueError( 

851 "If the `request` argument is set, then none of " 

852 "the individual field arguments should be set." 

853 ) 

854 

855 # Minor optimization to avoid making a copy if the user passes 

856 # in a logging.ListLogEntriesRequest. 

857 # There's no risk of modifying the input as we've already verified 

858 # there are no flattened fields. 

859 if not isinstance(request, logging.ListLogEntriesRequest): 

860 request = logging.ListLogEntriesRequest(request) 

861 # If we have keyword arguments corresponding to fields on the 

862 # request, apply these. 

863 if resource_names is not None: 

864 request.resource_names = resource_names 

865 if filter is not None: 

866 request.filter = filter 

867 if order_by is not None: 

868 request.order_by = order_by 

869 

870 # Wrap the RPC method; this adds retry and timeout information, 

871 # and friendly error handling. 

872 rpc = self._transport._wrapped_methods[self._transport.list_log_entries] 

873 

874 # Send the request. 

875 response = rpc( 

876 request, 

877 retry=retry, 

878 timeout=timeout, 

879 metadata=metadata, 

880 ) 

881 

882 # This method is paged; wrap the response in a pager, which provides 

883 # an `__iter__` convenience method. 

884 response = pagers.ListLogEntriesPager( 

885 method=rpc, 

886 request=request, 

887 response=response, 

888 metadata=metadata, 

889 ) 

890 

891 # Done; return the response. 

892 return response 

893 

894 def list_monitored_resource_descriptors( 

895 self, 

896 request: Optional[ 

897 Union[logging.ListMonitoredResourceDescriptorsRequest, dict] 

898 ] = None, 

899 *, 

900 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

901 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

902 metadata: Sequence[Tuple[str, str]] = (), 

903 ) -> pagers.ListMonitoredResourceDescriptorsPager: 

904 r"""Lists the descriptors for monitored resource types 

905 used by Logging. 

906 

907 .. code-block:: python 

908 

909 # This snippet has been automatically generated and should be regarded as a 

910 # code template only. 

911 # It will require modifications to work: 

912 # - It may require correct/in-range values for request initialization. 

913 # - It may require specifying regional endpoints when creating the service 

914 # client as shown in: 

915 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

916 from google.cloud import logging_v2 

917 

918 def sample_list_monitored_resource_descriptors(): 

919 # Create a client 

920 client = logging_v2.LoggingServiceV2Client() 

921 

922 # Initialize request argument(s) 

923 request = logging_v2.ListMonitoredResourceDescriptorsRequest( 

924 ) 

925 

926 # Make the request 

927 page_result = client.list_monitored_resource_descriptors(request=request) 

928 

929 # Handle the response 

930 for response in page_result: 

931 print(response) 

932 

933 Args: 

934 request (Union[google.cloud.logging_v2.types.ListMonitoredResourceDescriptorsRequest, dict]): 

935 The request object. The parameters to 

936 ListMonitoredResourceDescriptors 

937 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

938 should be retried. 

939 timeout (float): The timeout for this request. 

940 metadata (Sequence[Tuple[str, str]]): Strings which should be 

941 sent along with the request as metadata. 

942 

943 Returns: 

944 google.cloud.logging_v2.services.logging_service_v2.pagers.ListMonitoredResourceDescriptorsPager: 

945 Result returned from 

946 ListMonitoredResourceDescriptors. 

947 Iterating over this object will yield 

948 results and resolve additional pages 

949 automatically. 

950 

951 """ 

952 # Create or coerce a protobuf request object. 

953 # Minor optimization to avoid making a copy if the user passes 

954 # in a logging.ListMonitoredResourceDescriptorsRequest. 

955 # There's no risk of modifying the input as we've already verified 

956 # there are no flattened fields. 

957 if not isinstance(request, logging.ListMonitoredResourceDescriptorsRequest): 

958 request = logging.ListMonitoredResourceDescriptorsRequest(request) 

959 

960 # Wrap the RPC method; this adds retry and timeout information, 

961 # and friendly error handling. 

962 rpc = self._transport._wrapped_methods[ 

963 self._transport.list_monitored_resource_descriptors 

964 ] 

965 

966 # Send the request. 

967 response = rpc( 

968 request, 

969 retry=retry, 

970 timeout=timeout, 

971 metadata=metadata, 

972 ) 

973 

974 # This method is paged; wrap the response in a pager, which provides 

975 # an `__iter__` convenience method. 

976 response = pagers.ListMonitoredResourceDescriptorsPager( 

977 method=rpc, 

978 request=request, 

979 response=response, 

980 metadata=metadata, 

981 ) 

982 

983 # Done; return the response. 

984 return response 

985 

986 def list_logs( 

987 self, 

988 request: Optional[Union[logging.ListLogsRequest, dict]] = None, 

989 *, 

990 parent: Optional[str] = None, 

991 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

992 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

993 metadata: Sequence[Tuple[str, str]] = (), 

994 ) -> pagers.ListLogsPager: 

995 r"""Lists the logs in projects, organizations, folders, 

996 or billing accounts. Only logs that have entries are 

997 listed. 

998 

999 .. code-block:: python 

1000 

1001 # This snippet has been automatically generated and should be regarded as a 

1002 # code template only. 

1003 # It will require modifications to work: 

1004 # - It may require correct/in-range values for request initialization. 

1005 # - It may require specifying regional endpoints when creating the service 

1006 # client as shown in: 

1007 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1008 from google.cloud import logging_v2 

1009 

1010 def sample_list_logs(): 

1011 # Create a client 

1012 client = logging_v2.LoggingServiceV2Client() 

1013 

1014 # Initialize request argument(s) 

1015 request = logging_v2.ListLogsRequest( 

1016 parent="parent_value", 

1017 ) 

1018 

1019 # Make the request 

1020 page_result = client.list_logs(request=request) 

1021 

1022 # Handle the response 

1023 for response in page_result: 

1024 print(response) 

1025 

1026 Args: 

1027 request (Union[google.cloud.logging_v2.types.ListLogsRequest, dict]): 

1028 The request object. The parameters to ListLogs. 

1029 parent (str): 

1030 Required. The resource name that owns the logs: 

1031 

1032 - ``projects/[PROJECT_ID]`` 

1033 - ``organizations/[ORGANIZATION_ID]`` 

1034 - ``billingAccounts/[BILLING_ACCOUNT_ID]`` 

1035 - ``folders/[FOLDER_ID]`` 

1036 

1037 This corresponds to the ``parent`` field 

1038 on the ``request`` instance; if ``request`` is provided, this 

1039 should not be set. 

1040 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1041 should be retried. 

1042 timeout (float): The timeout for this request. 

1043 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1044 sent along with the request as metadata. 

1045 

1046 Returns: 

1047 google.cloud.logging_v2.services.logging_service_v2.pagers.ListLogsPager: 

1048 Result returned from ListLogs. 

1049 Iterating over this object will yield 

1050 results and resolve additional pages 

1051 automatically. 

1052 

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 ) 

1063 

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 

1074 

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] 

1078 

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 ) 

1084 

1085 # Send the request. 

1086 response = rpc( 

1087 request, 

1088 retry=retry, 

1089 timeout=timeout, 

1090 metadata=metadata, 

1091 ) 

1092 

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 ) 

1101 

1102 # Done; return the response. 

1103 return response 

1104 

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. 

1116 

1117 .. code-block:: python 

1118 

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 

1127 

1128 def sample_tail_log_entries(): 

1129 # Create a client 

1130 client = logging_v2.LoggingServiceV2Client() 

1131 

1132 # Initialize request argument(s) 

1133 request = logging_v2.TailLogEntriesRequest( 

1134 resource_names=['resource_names_value1', 'resource_names_value2'], 

1135 ) 

1136 

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] 

1142 

1143 def request_generator(): 

1144 for request in requests: 

1145 yield request 

1146 

1147 # Make the request 

1148 stream = client.tail_log_entries(requests=request_generator()) 

1149 

1150 # Handle the response 

1151 for response in stream: 

1152 print(response) 

1153 

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. 

1162 

1163 Returns: 

1164 Iterable[google.cloud.logging_v2.types.TailLogEntriesResponse]: 

1165 Result returned from TailLogEntries. 

1166 """ 

1167 

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] 

1171 

1172 # Send the request. 

1173 response = rpc( 

1174 requests, 

1175 retry=retry, 

1176 timeout=timeout, 

1177 metadata=metadata, 

1178 ) 

1179 

1180 # Done; return the response. 

1181 return response 

1182 

1183 def __enter__(self) -> "LoggingServiceV2Client": 

1184 return self 

1185 

1186 def __exit__(self, type, value, traceback): 

1187 """Releases underlying transport's resources. 

1188 

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() 

1195 

1196 

1197DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1198 gapic_version=package_version.__version__ 

1199) 

1200 

1201 

1202__all__ = ("LoggingServiceV2Client",)