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

216 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 Sequence, 

26 Tuple, 

27 Type, 

28 Union, 

29 cast, 

30) 

31 

32from google.cloud.logging_v2 import gapic_version as package_version 

33 

34from google.api_core import client_options as client_options_lib 

35from google.api_core import exceptions as core_exceptions 

36from google.api_core import gapic_v1 

37from google.api_core import retry as retries 

38from google.auth import credentials as ga_credentials # type: ignore 

39from google.auth.transport import mtls # type: ignore 

40from google.auth.transport.grpc import SslCredentials # type: ignore 

41from google.auth.exceptions import MutualTLSChannelError # type: ignore 

42from google.oauth2 import service_account # type: ignore 

43 

44try: 

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

46except AttributeError: # pragma: NO COVER 

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

48 

49from google.api import distribution_pb2 # type: ignore 

50from google.api import metric_pb2 # type: ignore 

51from google.cloud.logging_v2.services.metrics_service_v2 import pagers 

52from google.cloud.logging_v2.types import logging_metrics 

53from google.protobuf import timestamp_pb2 # type: ignore 

54from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO 

55from .transports.grpc import MetricsServiceV2GrpcTransport 

56from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport 

57 

58 

59class MetricsServiceV2ClientMeta(type): 

60 """Metaclass for the MetricsServiceV2 client. 

61 

62 This provides class-level methods for building and retrieving 

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

64 objects. 

65 """ 

66 

67 _transport_registry = ( 

68 OrderedDict() 

69 ) # type: Dict[str, Type[MetricsServiceV2Transport]] 

70 _transport_registry["grpc"] = MetricsServiceV2GrpcTransport 

71 _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport 

72 

73 def get_transport_class( 

74 cls, 

75 label: Optional[str] = None, 

76 ) -> Type[MetricsServiceV2Transport]: 

77 """Returns an appropriate transport class. 

78 

79 Args: 

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

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

82 

83 Returns: 

84 The transport class to use. 

85 """ 

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

87 if label: 

88 return cls._transport_registry[label] 

89 

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

91 # in the dictionary). 

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

93 

94 

95class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta): 

96 """Service for configuring logs-based metrics.""" 

97 

98 @staticmethod 

99 def _get_default_mtls_endpoint(api_endpoint): 

100 """Converts api endpoint to mTLS endpoint. 

101 

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

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

104 Args: 

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

106 Returns: 

107 str: converted mTLS api endpoint. 

108 """ 

109 if not api_endpoint: 

110 return api_endpoint 

111 

112 mtls_endpoint_re = re.compile( 

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

114 ) 

115 

116 m = mtls_endpoint_re.match(api_endpoint) 

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

118 if mtls or not googledomain: 

119 return api_endpoint 

120 

121 if sandbox: 

122 return api_endpoint.replace( 

123 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

124 ) 

125 

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

127 

128 DEFAULT_ENDPOINT = "logging.googleapis.com" 

129 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

130 DEFAULT_ENDPOINT 

131 ) 

132 

133 @classmethod 

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

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

136 info. 

137 

138 Args: 

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

140 args: Additional arguments to pass to the constructor. 

141 kwargs: Additional arguments to pass to the constructor. 

142 

143 Returns: 

144 MetricsServiceV2Client: The constructed client. 

145 """ 

146 credentials = service_account.Credentials.from_service_account_info(info) 

147 kwargs["credentials"] = credentials 

148 return cls(*args, **kwargs) 

149 

150 @classmethod 

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

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

153 file. 

154 

155 Args: 

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

157 file. 

158 args: Additional arguments to pass to the constructor. 

159 kwargs: Additional arguments to pass to the constructor. 

160 

161 Returns: 

162 MetricsServiceV2Client: The constructed client. 

163 """ 

164 credentials = service_account.Credentials.from_service_account_file(filename) 

165 kwargs["credentials"] = credentials 

166 return cls(*args, **kwargs) 

167 

168 from_service_account_json = from_service_account_file 

169 

170 @property 

171 def transport(self) -> MetricsServiceV2Transport: 

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

173 

174 Returns: 

175 MetricsServiceV2Transport: The transport used by the client 

176 instance. 

177 """ 

178 return self._transport 

179 

180 @staticmethod 

181 def log_metric_path( 

182 project: str, 

183 metric: str, 

184 ) -> str: 

185 """Returns a fully-qualified log_metric string.""" 

186 return "projects/{project}/metrics/{metric}".format( 

187 project=project, 

188 metric=metric, 

189 ) 

190 

191 @staticmethod 

192 def parse_log_metric_path(path: str) -> Dict[str, str]: 

193 """Parses a log_metric path into its component segments.""" 

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

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

196 

197 @staticmethod 

198 def common_billing_account_path( 

199 billing_account: str, 

200 ) -> str: 

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

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

203 billing_account=billing_account, 

204 ) 

205 

206 @staticmethod 

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

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

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

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

211 

212 @staticmethod 

213 def common_folder_path( 

214 folder: str, 

215 ) -> str: 

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

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

218 folder=folder, 

219 ) 

220 

221 @staticmethod 

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

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

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

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

226 

227 @staticmethod 

228 def common_organization_path( 

229 organization: str, 

230 ) -> str: 

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

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

233 organization=organization, 

234 ) 

235 

236 @staticmethod 

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

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

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

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

241 

242 @staticmethod 

243 def common_project_path( 

244 project: str, 

245 ) -> str: 

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

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

248 project=project, 

249 ) 

250 

251 @staticmethod 

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

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

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

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

256 

257 @staticmethod 

258 def common_location_path( 

259 project: str, 

260 location: str, 

261 ) -> str: 

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

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

264 project=project, 

265 location=location, 

266 ) 

267 

268 @staticmethod 

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

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

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

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

273 

274 @classmethod 

275 def get_mtls_endpoint_and_cert_source( 

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

277 ): 

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

279 

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

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

282 client cert source is None. 

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

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

285 source is None. 

286 

287 The API endpoint is determined in the following order: 

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

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

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

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

292 use the default API endpoint. 

293 

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

295 

296 Args: 

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

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

299 in this method. 

300 

301 Returns: 

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

303 client cert source to use. 

304 

305 Raises: 

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

307 """ 

308 if client_options is None: 

309 client_options = client_options_lib.ClientOptions() 

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

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

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

313 raise ValueError( 

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

315 ) 

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

317 raise MutualTLSChannelError( 

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

319 ) 

320 

321 # Figure out the client cert source to use. 

322 client_cert_source = None 

323 if use_client_cert == "true": 

324 if client_options.client_cert_source: 

325 client_cert_source = client_options.client_cert_source 

326 elif mtls.has_default_client_cert_source(): 

327 client_cert_source = mtls.default_client_cert_source() 

328 

329 # Figure out which api endpoint to use. 

330 if client_options.api_endpoint is not None: 

331 api_endpoint = client_options.api_endpoint 

332 elif use_mtls_endpoint == "always" or ( 

333 use_mtls_endpoint == "auto" and client_cert_source 

334 ): 

335 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

336 else: 

337 api_endpoint = cls.DEFAULT_ENDPOINT 

338 

339 return api_endpoint, client_cert_source 

340 

341 def __init__( 

342 self, 

343 *, 

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

345 transport: Optional[Union[str, MetricsServiceV2Transport]] = None, 

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

347 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

348 ) -> None: 

349 """Instantiates the metrics service v2 client. 

350 

351 Args: 

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

353 authorization credentials to attach to requests. These 

354 credentials identify the application to the service; if none 

355 are specified, the client will attempt to ascertain the 

356 credentials from the environment. 

357 transport (Union[str, MetricsServiceV2Transport]): The 

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

359 automatically. 

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

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

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

363 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT 

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

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

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

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

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

369 precedence if provided. 

370 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

372 to provide client certificate for mutual TLS transport. If 

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

374 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

375 set, no client certificate will be used. 

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

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

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

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

380 your own client library. 

381 

382 Raises: 

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

384 creation failed for any reason. 

385 """ 

386 if isinstance(client_options, dict): 

387 client_options = client_options_lib.from_dict(client_options) 

388 if client_options is None: 

389 client_options = client_options_lib.ClientOptions() 

390 client_options = cast(client_options_lib.ClientOptions, client_options) 

391 

392 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( 

393 client_options 

394 ) 

395 

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

397 if api_key_value and credentials: 

398 raise ValueError( 

399 "client_options.api_key and credentials are mutually exclusive" 

400 ) 

401 

402 # Save or instantiate the transport. 

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

404 # instance provides an extensibility point for unusual situations. 

405 if isinstance(transport, MetricsServiceV2Transport): 

406 # transport is a MetricsServiceV2Transport instance. 

407 if credentials or client_options.credentials_file or api_key_value: 

408 raise ValueError( 

409 "When providing a transport instance, " 

410 "provide its credentials directly." 

411 ) 

412 if client_options.scopes: 

413 raise ValueError( 

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

415 "directly." 

416 ) 

417 self._transport = transport 

418 else: 

419 import google.auth._default # type: ignore 

420 

421 if api_key_value and hasattr( 

422 google.auth._default, "get_api_key_credentials" 

423 ): 

424 credentials = google.auth._default.get_api_key_credentials( 

425 api_key_value 

426 ) 

427 

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

429 self._transport = Transport( 

430 credentials=credentials, 

431 credentials_file=client_options.credentials_file, 

432 host=api_endpoint, 

433 scopes=client_options.scopes, 

434 client_cert_source_for_mtls=client_cert_source_func, 

435 quota_project_id=client_options.quota_project_id, 

436 client_info=client_info, 

437 always_use_jwt_access=True, 

438 api_audience=client_options.api_audience, 

439 ) 

440 

441 def list_log_metrics( 

442 self, 

443 request: Optional[Union[logging_metrics.ListLogMetricsRequest, dict]] = None, 

444 *, 

445 parent: Optional[str] = None, 

446 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

449 ) -> pagers.ListLogMetricsPager: 

450 r"""Lists logs-based metrics. 

451 

452 .. code-block:: python 

453 

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

455 # code template only. 

456 # It will require modifications to work: 

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

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

459 # client as shown in: 

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

461 from google.cloud import logging_v2 

462 

463 def sample_list_log_metrics(): 

464 # Create a client 

465 client = logging_v2.MetricsServiceV2Client() 

466 

467 # Initialize request argument(s) 

468 request = logging_v2.ListLogMetricsRequest( 

469 parent="parent_value", 

470 ) 

471 

472 # Make the request 

473 page_result = client.list_log_metrics(request=request) 

474 

475 # Handle the response 

476 for response in page_result: 

477 print(response) 

478 

479 Args: 

480 request (Union[google.cloud.logging_v2.types.ListLogMetricsRequest, dict]): 

481 The request object. The parameters to ListLogMetrics. 

482 parent (str): 

483 Required. The name of the project containing the 

484 metrics: 

485 

486 :: 

487 

488 "projects/[PROJECT_ID]" 

489 

490 This corresponds to the ``parent`` field 

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

492 should not be set. 

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

494 should be retried. 

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

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

497 sent along with the request as metadata. 

498 

499 Returns: 

500 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsPager: 

501 Result returned from ListLogMetrics. 

502 Iterating over this object will yield 

503 results and resolve additional pages 

504 automatically. 

505 

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([parent]) 

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_metrics.ListLogMetricsRequest. 

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_metrics.ListLogMetricsRequest): 

522 request = logging_metrics.ListLogMetricsRequest(request) 

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

524 # request, apply these. 

525 if parent is not None: 

526 request.parent = parent 

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.list_log_metrics] 

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((("parent", request.parent),)), 

536 ) 

537 

538 # Send the request. 

539 response = rpc( 

540 request, 

541 retry=retry, 

542 timeout=timeout, 

543 metadata=metadata, 

544 ) 

545 

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

547 # an `__iter__` convenience method. 

548 response = pagers.ListLogMetricsPager( 

549 method=rpc, 

550 request=request, 

551 response=response, 

552 metadata=metadata, 

553 ) 

554 

555 # Done; return the response. 

556 return response 

557 

558 def get_log_metric( 

559 self, 

560 request: Optional[Union[logging_metrics.GetLogMetricRequest, dict]] = None, 

561 *, 

562 metric_name: Optional[str] = None, 

563 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

566 ) -> logging_metrics.LogMetric: 

567 r"""Gets a logs-based metric. 

568 

569 .. code-block:: python 

570 

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

572 # code template only. 

573 # It will require modifications to work: 

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

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

576 # client as shown in: 

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

578 from google.cloud import logging_v2 

579 

580 def sample_get_log_metric(): 

581 # Create a client 

582 client = logging_v2.MetricsServiceV2Client() 

583 

584 # Initialize request argument(s) 

585 request = logging_v2.GetLogMetricRequest( 

586 metric_name="metric_name_value", 

587 ) 

588 

589 # Make the request 

590 response = client.get_log_metric(request=request) 

591 

592 # Handle the response 

593 print(response) 

594 

595 Args: 

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

597 The request object. The parameters to GetLogMetric. 

598 metric_name (str): 

599 Required. The resource name of the desired metric: 

600 

601 :: 

602 

603 "projects/[PROJECT_ID]/metrics/[METRIC_ID]" 

604 

605 This corresponds to the ``metric_name`` field 

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

607 should not be set. 

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

609 should be retried. 

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

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

612 sent along with the request as metadata. 

613 

614 Returns: 

615 google.cloud.logging_v2.types.LogMetric: 

616 Describes a logs-based metric. The 

617 value of the metric is the number of log 

618 entries that match a logs filter in a 

619 given time interval. 

620 Logs-based metrics can also be used to 

621 extract values from logs and create a 

622 distribution of the values. The 

623 distribution records the statistics of 

624 the extracted values along with an 

625 optional histogram of the values as 

626 specified by the bucket options. 

627 

628 """ 

629 # Create or coerce a protobuf request object. 

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

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

632 has_flattened_params = any([metric_name]) 

633 if request is not None and has_flattened_params: 

634 raise ValueError( 

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

636 "the individual field arguments should be set." 

637 ) 

638 

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

640 # in a logging_metrics.GetLogMetricRequest. 

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

642 # there are no flattened fields. 

643 if not isinstance(request, logging_metrics.GetLogMetricRequest): 

644 request = logging_metrics.GetLogMetricRequest(request) 

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

646 # request, apply these. 

647 if metric_name is not None: 

648 request.metric_name = metric_name 

649 

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

651 # and friendly error handling. 

652 rpc = self._transport._wrapped_methods[self._transport.get_log_metric] 

653 

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

655 # add these here. 

656 metadata = tuple(metadata) + ( 

657 gapic_v1.routing_header.to_grpc_metadata( 

658 (("metric_name", request.metric_name),) 

659 ), 

660 ) 

661 

662 # Send the request. 

663 response = rpc( 

664 request, 

665 retry=retry, 

666 timeout=timeout, 

667 metadata=metadata, 

668 ) 

669 

670 # Done; return the response. 

671 return response 

672 

673 def create_log_metric( 

674 self, 

675 request: Optional[Union[logging_metrics.CreateLogMetricRequest, dict]] = None, 

676 *, 

677 parent: Optional[str] = None, 

678 metric: Optional[logging_metrics.LogMetric] = None, 

679 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

682 ) -> logging_metrics.LogMetric: 

683 r"""Creates a logs-based metric. 

684 

685 .. code-block:: python 

686 

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

688 # code template only. 

689 # It will require modifications to work: 

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

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

692 # client as shown in: 

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

694 from google.cloud import logging_v2 

695 

696 def sample_create_log_metric(): 

697 # Create a client 

698 client = logging_v2.MetricsServiceV2Client() 

699 

700 # Initialize request argument(s) 

701 metric = logging_v2.LogMetric() 

702 metric.name = "name_value" 

703 metric.filter = "filter_value" 

704 

705 request = logging_v2.CreateLogMetricRequest( 

706 parent="parent_value", 

707 metric=metric, 

708 ) 

709 

710 # Make the request 

711 response = client.create_log_metric(request=request) 

712 

713 # Handle the response 

714 print(response) 

715 

716 Args: 

717 request (Union[google.cloud.logging_v2.types.CreateLogMetricRequest, dict]): 

718 The request object. The parameters to CreateLogMetric. 

719 parent (str): 

720 Required. The resource name of the project in which to 

721 create the metric: 

722 

723 :: 

724 

725 "projects/[PROJECT_ID]" 

726 

727 The new metric must be provided in the request. 

728 

729 This corresponds to the ``parent`` field 

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

731 should not be set. 

732 metric (google.cloud.logging_v2.types.LogMetric): 

733 Required. The new logs-based metric, 

734 which must not have an identifier that 

735 already exists. 

736 

737 This corresponds to the ``metric`` field 

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

739 should not be set. 

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

741 should be retried. 

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

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

744 sent along with the request as metadata. 

745 

746 Returns: 

747 google.cloud.logging_v2.types.LogMetric: 

748 Describes a logs-based metric. The 

749 value of the metric is the number of log 

750 entries that match a logs filter in a 

751 given time interval. 

752 Logs-based metrics can also be used to 

753 extract values from logs and create a 

754 distribution of the values. The 

755 distribution records the statistics of 

756 the extracted values along with an 

757 optional histogram of the values as 

758 specified by the bucket options. 

759 

760 """ 

761 # Create or coerce a protobuf request object. 

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

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

764 has_flattened_params = any([parent, metric]) 

765 if request is not None and has_flattened_params: 

766 raise ValueError( 

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

768 "the individual field arguments should be set." 

769 ) 

770 

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

772 # in a logging_metrics.CreateLogMetricRequest. 

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

774 # there are no flattened fields. 

775 if not isinstance(request, logging_metrics.CreateLogMetricRequest): 

776 request = logging_metrics.CreateLogMetricRequest(request) 

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

778 # request, apply these. 

779 if parent is not None: 

780 request.parent = parent 

781 if metric is not None: 

782 request.metric = metric 

783 

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

785 # and friendly error handling. 

786 rpc = self._transport._wrapped_methods[self._transport.create_log_metric] 

787 

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

789 # add these here. 

790 metadata = tuple(metadata) + ( 

791 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

792 ) 

793 

794 # Send the request. 

795 response = rpc( 

796 request, 

797 retry=retry, 

798 timeout=timeout, 

799 metadata=metadata, 

800 ) 

801 

802 # Done; return the response. 

803 return response 

804 

805 def update_log_metric( 

806 self, 

807 request: Optional[Union[logging_metrics.UpdateLogMetricRequest, dict]] = None, 

808 *, 

809 metric_name: Optional[str] = None, 

810 metric: Optional[logging_metrics.LogMetric] = None, 

811 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

814 ) -> logging_metrics.LogMetric: 

815 r"""Creates or updates a logs-based metric. 

816 

817 .. code-block:: python 

818 

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

820 # code template only. 

821 # It will require modifications to work: 

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

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

824 # client as shown in: 

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

826 from google.cloud import logging_v2 

827 

828 def sample_update_log_metric(): 

829 # Create a client 

830 client = logging_v2.MetricsServiceV2Client() 

831 

832 # Initialize request argument(s) 

833 metric = logging_v2.LogMetric() 

834 metric.name = "name_value" 

835 metric.filter = "filter_value" 

836 

837 request = logging_v2.UpdateLogMetricRequest( 

838 metric_name="metric_name_value", 

839 metric=metric, 

840 ) 

841 

842 # Make the request 

843 response = client.update_log_metric(request=request) 

844 

845 # Handle the response 

846 print(response) 

847 

848 Args: 

849 request (Union[google.cloud.logging_v2.types.UpdateLogMetricRequest, dict]): 

850 The request object. The parameters to UpdateLogMetric. 

851 metric_name (str): 

852 Required. The resource name of the metric to update: 

853 

854 :: 

855 

856 "projects/[PROJECT_ID]/metrics/[METRIC_ID]" 

857 

858 The updated metric must be provided in the request and 

859 it's ``name`` field must be the same as ``[METRIC_ID]`` 

860 If the metric does not exist in ``[PROJECT_ID]``, then a 

861 new metric is created. 

862 

863 This corresponds to the ``metric_name`` field 

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

865 should not be set. 

866 metric (google.cloud.logging_v2.types.LogMetric): 

867 Required. The updated metric. 

868 This corresponds to the ``metric`` field 

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

870 should not be set. 

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

872 should be retried. 

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

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

875 sent along with the request as metadata. 

876 

877 Returns: 

878 google.cloud.logging_v2.types.LogMetric: 

879 Describes a logs-based metric. The 

880 value of the metric is the number of log 

881 entries that match a logs filter in a 

882 given time interval. 

883 Logs-based metrics can also be used to 

884 extract values from logs and create a 

885 distribution of the values. The 

886 distribution records the statistics of 

887 the extracted values along with an 

888 optional histogram of the values as 

889 specified by the bucket options. 

890 

891 """ 

892 # Create or coerce a protobuf request object. 

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

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

895 has_flattened_params = any([metric_name, metric]) 

896 if request is not None and has_flattened_params: 

897 raise ValueError( 

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

899 "the individual field arguments should be set." 

900 ) 

901 

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

903 # in a logging_metrics.UpdateLogMetricRequest. 

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

905 # there are no flattened fields. 

906 if not isinstance(request, logging_metrics.UpdateLogMetricRequest): 

907 request = logging_metrics.UpdateLogMetricRequest(request) 

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

909 # request, apply these. 

910 if metric_name is not None: 

911 request.metric_name = metric_name 

912 if metric is not None: 

913 request.metric = metric 

914 

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

916 # and friendly error handling. 

917 rpc = self._transport._wrapped_methods[self._transport.update_log_metric] 

918 

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

920 # add these here. 

921 metadata = tuple(metadata) + ( 

922 gapic_v1.routing_header.to_grpc_metadata( 

923 (("metric_name", request.metric_name),) 

924 ), 

925 ) 

926 

927 # Send the request. 

928 response = rpc( 

929 request, 

930 retry=retry, 

931 timeout=timeout, 

932 metadata=metadata, 

933 ) 

934 

935 # Done; return the response. 

936 return response 

937 

938 def delete_log_metric( 

939 self, 

940 request: Optional[Union[logging_metrics.DeleteLogMetricRequest, dict]] = None, 

941 *, 

942 metric_name: Optional[str] = None, 

943 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

946 ) -> None: 

947 r"""Deletes a logs-based metric. 

948 

949 .. code-block:: python 

950 

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

952 # code template only. 

953 # It will require modifications to work: 

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

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

956 # client as shown in: 

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

958 from google.cloud import logging_v2 

959 

960 def sample_delete_log_metric(): 

961 # Create a client 

962 client = logging_v2.MetricsServiceV2Client() 

963 

964 # Initialize request argument(s) 

965 request = logging_v2.DeleteLogMetricRequest( 

966 metric_name="metric_name_value", 

967 ) 

968 

969 # Make the request 

970 client.delete_log_metric(request=request) 

971 

972 Args: 

973 request (Union[google.cloud.logging_v2.types.DeleteLogMetricRequest, dict]): 

974 The request object. The parameters to DeleteLogMetric. 

975 metric_name (str): 

976 Required. The resource name of the metric to delete: 

977 

978 :: 

979 

980 "projects/[PROJECT_ID]/metrics/[METRIC_ID]" 

981 

982 This corresponds to the ``metric_name`` field 

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

984 should not be set. 

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

986 should be retried. 

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

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

989 sent along with the request as metadata. 

990 """ 

991 # Create or coerce a protobuf request object. 

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

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

994 has_flattened_params = any([metric_name]) 

995 if request is not None and has_flattened_params: 

996 raise ValueError( 

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

998 "the individual field arguments should be set." 

999 ) 

1000 

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

1002 # in a logging_metrics.DeleteLogMetricRequest. 

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

1004 # there are no flattened fields. 

1005 if not isinstance(request, logging_metrics.DeleteLogMetricRequest): 

1006 request = logging_metrics.DeleteLogMetricRequest(request) 

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

1008 # request, apply these. 

1009 if metric_name is not None: 

1010 request.metric_name = metric_name 

1011 

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

1013 # and friendly error handling. 

1014 rpc = self._transport._wrapped_methods[self._transport.delete_log_metric] 

1015 

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

1017 # add these here. 

1018 metadata = tuple(metadata) + ( 

1019 gapic_v1.routing_header.to_grpc_metadata( 

1020 (("metric_name", request.metric_name),) 

1021 ), 

1022 ) 

1023 

1024 # Send the request. 

1025 rpc( 

1026 request, 

1027 retry=retry, 

1028 timeout=timeout, 

1029 metadata=metadata, 

1030 ) 

1031 

1032 def __enter__(self) -> "MetricsServiceV2Client": 

1033 return self 

1034 

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

1036 """Releases underlying transport's resources. 

1037 

1038 .. warning:: 

1039 ONLY use as a context manager if the transport is NOT shared 

1040 with other clients! Exiting the with block will CLOSE the transport 

1041 and may cause errors in other clients! 

1042 """ 

1043 self.transport.close() 

1044 

1045 

1046DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1047 gapic_version=package_version.__version__ 

1048) 

1049 

1050 

1051__all__ = ("MetricsServiceV2Client",)