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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

337 statements  

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

2# Copyright 2025 Google LLC 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17from http import HTTPStatus 

18import json 

19import logging as std_logging 

20import os 

21import re 

22from typing import ( 

23 Dict, 

24 Callable, 

25 Mapping, 

26 MutableMapping, 

27 MutableSequence, 

28 Optional, 

29 Sequence, 

30 Tuple, 

31 Type, 

32 Union, 

33 cast, 

34) 

35import uuid 

36import warnings 

37 

38from google.cloud.logging_v2 import gapic_version as package_version 

39 

40from google.api_core import client_options as client_options_lib 

41from google.api_core import exceptions as core_exceptions 

42from google.api_core import gapic_v1 

43from google.api_core import retry as retries 

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

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

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

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

48from google.oauth2 import service_account # type: ignore 

49import google.protobuf 

50 

51try: 

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

53except AttributeError: # pragma: NO COVER 

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

55 

56try: 

57 from google.api_core import client_logging # type: ignore 

58 

59 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

60except ImportError: # pragma: NO COVER 

61 CLIENT_LOGGING_SUPPORTED = False 

62 

63_LOGGER = std_logging.getLogger(__name__) 

64 

65from google.api import distribution_pb2 # type: ignore 

66from google.api import metric_pb2 # type: ignore 

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

68from google.cloud.logging_v2.types import logging_metrics 

69from google.longrunning import operations_pb2 # type: ignore 

70from google.protobuf import timestamp_pb2 # type: ignore 

71from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO 

72from .transports.grpc import MetricsServiceV2GrpcTransport 

73from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport 

74 

75 

76class MetricsServiceV2ClientMeta(type): 

77 """Metaclass for the MetricsServiceV2 client. 

78 

79 This provides class-level methods for building and retrieving 

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

81 objects. 

82 """ 

83 

84 _transport_registry = ( 

85 OrderedDict() 

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

87 _transport_registry["grpc"] = MetricsServiceV2GrpcTransport 

88 _transport_registry["grpc_asyncio"] = MetricsServiceV2GrpcAsyncIOTransport 

89 

90 def get_transport_class( 

91 cls, 

92 label: Optional[str] = None, 

93 ) -> Type[MetricsServiceV2Transport]: 

94 """Returns an appropriate transport class. 

95 

96 Args: 

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

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

99 

100 Returns: 

101 The transport class to use. 

102 """ 

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

104 if label: 

105 return cls._transport_registry[label] 

106 

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

108 # in the dictionary). 

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

110 

111 

112class MetricsServiceV2Client(metaclass=MetricsServiceV2ClientMeta): 

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

114 

115 @staticmethod 

116 def _get_default_mtls_endpoint(api_endpoint): 

117 """Converts api endpoint to mTLS endpoint. 

118 

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

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

121 Args: 

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

123 Returns: 

124 str: converted mTLS api endpoint. 

125 """ 

126 if not api_endpoint: 

127 return api_endpoint 

128 

129 mtls_endpoint_re = re.compile( 

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

131 ) 

132 

133 m = mtls_endpoint_re.match(api_endpoint) 

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

135 if mtls or not googledomain: 

136 return api_endpoint 

137 

138 if sandbox: 

139 return api_endpoint.replace( 

140 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

141 ) 

142 

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

144 

145 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. 

146 DEFAULT_ENDPOINT = "logging.googleapis.com" 

147 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

148 DEFAULT_ENDPOINT 

149 ) 

150 

151 _DEFAULT_ENDPOINT_TEMPLATE = "logging.{UNIVERSE_DOMAIN}" 

152 _DEFAULT_UNIVERSE = "googleapis.com" 

153 

154 @staticmethod 

155 def _use_client_cert_effective(): 

156 """Returns whether client certificate should be used for mTLS if the 

157 google-auth version supports should_use_client_cert automatic mTLS enablement. 

158 

159 Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. 

160 

161 Returns: 

162 bool: whether client certificate should be used for mTLS 

163 Raises: 

164 ValueError: (If using a version of google-auth without should_use_client_cert and 

165 GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) 

166 """ 

167 # check if google-auth version supports should_use_client_cert for automatic mTLS enablement 

168 if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER 

169 return mtls.should_use_client_cert() 

170 else: # pragma: NO COVER 

171 # if unsupported, fallback to reading from env var 

172 use_client_cert_str = os.getenv( 

173 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

174 ).lower() 

175 if use_client_cert_str not in ("true", "false"): 

176 raise ValueError( 

177 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" 

178 " either `true` or `false`" 

179 ) 

180 return use_client_cert_str == "true" 

181 

182 @classmethod 

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

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

185 info. 

186 

187 Args: 

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

189 args: Additional arguments to pass to the constructor. 

190 kwargs: Additional arguments to pass to the constructor. 

191 

192 Returns: 

193 MetricsServiceV2Client: The constructed client. 

194 """ 

195 credentials = service_account.Credentials.from_service_account_info(info) 

196 kwargs["credentials"] = credentials 

197 return cls(*args, **kwargs) 

198 

199 @classmethod 

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

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

202 file. 

203 

204 Args: 

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

206 file. 

207 args: Additional arguments to pass to the constructor. 

208 kwargs: Additional arguments to pass to the constructor. 

209 

210 Returns: 

211 MetricsServiceV2Client: The constructed client. 

212 """ 

213 credentials = service_account.Credentials.from_service_account_file(filename) 

214 kwargs["credentials"] = credentials 

215 return cls(*args, **kwargs) 

216 

217 from_service_account_json = from_service_account_file 

218 

219 @property 

220 def transport(self) -> MetricsServiceV2Transport: 

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

222 

223 Returns: 

224 MetricsServiceV2Transport: The transport used by the client 

225 instance. 

226 """ 

227 return self._transport 

228 

229 @staticmethod 

230 def log_metric_path( 

231 project: str, 

232 metric: str, 

233 ) -> str: 

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

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

236 project=project, 

237 metric=metric, 

238 ) 

239 

240 @staticmethod 

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

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

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

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

245 

246 @staticmethod 

247 def common_billing_account_path( 

248 billing_account: str, 

249 ) -> str: 

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

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

252 billing_account=billing_account, 

253 ) 

254 

255 @staticmethod 

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

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

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

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

260 

261 @staticmethod 

262 def common_folder_path( 

263 folder: str, 

264 ) -> str: 

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

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

267 folder=folder, 

268 ) 

269 

270 @staticmethod 

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

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

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

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

275 

276 @staticmethod 

277 def common_organization_path( 

278 organization: str, 

279 ) -> str: 

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

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

282 organization=organization, 

283 ) 

284 

285 @staticmethod 

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

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

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

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

290 

291 @staticmethod 

292 def common_project_path( 

293 project: str, 

294 ) -> str: 

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

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

297 project=project, 

298 ) 

299 

300 @staticmethod 

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

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

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

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

305 

306 @staticmethod 

307 def common_location_path( 

308 project: str, 

309 location: str, 

310 ) -> str: 

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

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

313 project=project, 

314 location=location, 

315 ) 

316 

317 @staticmethod 

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

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

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

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

322 

323 @classmethod 

324 def get_mtls_endpoint_and_cert_source( 

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

326 ): 

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

328 

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

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

331 client cert source is None. 

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

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

334 source is None. 

335 

336 The API endpoint is determined in the following order: 

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

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

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

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

341 use the default API endpoint. 

342 

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

344 

345 Args: 

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

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

348 in this method. 

349 

350 Returns: 

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

352 client cert source to use. 

353 

354 Raises: 

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

356 """ 

357 

358 warnings.warn( 

359 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", 

360 DeprecationWarning, 

361 ) 

362 if client_options is None: 

363 client_options = client_options_lib.ClientOptions() 

364 use_client_cert = MetricsServiceV2Client._use_client_cert_effective() 

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

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

367 raise MutualTLSChannelError( 

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

369 ) 

370 

371 # Figure out the client cert source to use. 

372 client_cert_source = None 

373 if use_client_cert: 

374 if client_options.client_cert_source: 

375 client_cert_source = client_options.client_cert_source 

376 elif mtls.has_default_client_cert_source(): 

377 client_cert_source = mtls.default_client_cert_source() 

378 

379 # Figure out which api endpoint to use. 

380 if client_options.api_endpoint is not None: 

381 api_endpoint = client_options.api_endpoint 

382 elif use_mtls_endpoint == "always" or ( 

383 use_mtls_endpoint == "auto" and client_cert_source 

384 ): 

385 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

386 else: 

387 api_endpoint = cls.DEFAULT_ENDPOINT 

388 

389 return api_endpoint, client_cert_source 

390 

391 @staticmethod 

392 def _read_environment_variables(): 

393 """Returns the environment variables used by the client. 

394 

395 Returns: 

396 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, 

397 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

398 

399 Raises: 

400 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

401 any of ["true", "false"]. 

402 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

403 is not any of ["auto", "never", "always"]. 

404 """ 

405 use_client_cert = MetricsServiceV2Client._use_client_cert_effective() 

406 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() 

407 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

409 raise MutualTLSChannelError( 

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

411 ) 

412 return use_client_cert, use_mtls_endpoint, universe_domain_env 

413 

414 @staticmethod 

415 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

416 """Return the client cert source to be used by the client. 

417 

418 Args: 

419 provided_cert_source (bytes): The client certificate source provided. 

420 use_cert_flag (bool): A flag indicating whether to use the client certificate. 

421 

422 Returns: 

423 bytes or None: The client cert source to be used by the client. 

424 """ 

425 client_cert_source = None 

426 if use_cert_flag: 

427 if provided_cert_source: 

428 client_cert_source = provided_cert_source 

429 elif mtls.has_default_client_cert_source(): 

430 client_cert_source = mtls.default_client_cert_source() 

431 return client_cert_source 

432 

433 @staticmethod 

434 def _get_api_endpoint( 

435 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

436 ): 

437 """Return the API endpoint used by the client. 

438 

439 Args: 

440 api_override (str): The API endpoint override. If specified, this is always 

441 the return value of this function and the other arguments are not used. 

442 client_cert_source (bytes): The client certificate source used by the client. 

443 universe_domain (str): The universe domain used by the client. 

444 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. 

445 Possible values are "always", "auto", or "never". 

446 

447 Returns: 

448 str: The API endpoint to be used by the client. 

449 """ 

450 if api_override is not None: 

451 api_endpoint = api_override 

452 elif use_mtls_endpoint == "always" or ( 

453 use_mtls_endpoint == "auto" and client_cert_source 

454 ): 

455 _default_universe = MetricsServiceV2Client._DEFAULT_UNIVERSE 

456 if universe_domain != _default_universe: 

457 raise MutualTLSChannelError( 

458 f"mTLS is not supported in any universe other than {_default_universe}." 

459 ) 

460 api_endpoint = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT 

461 else: 

462 api_endpoint = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE.format( 

463 UNIVERSE_DOMAIN=universe_domain 

464 ) 

465 return api_endpoint 

466 

467 @staticmethod 

468 def _get_universe_domain( 

469 client_universe_domain: Optional[str], universe_domain_env: Optional[str] 

470 ) -> str: 

471 """Return the universe domain used by the client. 

472 

473 Args: 

474 client_universe_domain (Optional[str]): The universe domain configured via the client options. 

475 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. 

476 

477 Returns: 

478 str: The universe domain to be used by the client. 

479 

480 Raises: 

481 ValueError: If the universe domain is an empty string. 

482 """ 

483 universe_domain = MetricsServiceV2Client._DEFAULT_UNIVERSE 

484 if client_universe_domain is not None: 

485 universe_domain = client_universe_domain 

486 elif universe_domain_env is not None: 

487 universe_domain = universe_domain_env 

488 if len(universe_domain.strip()) == 0: 

489 raise ValueError("Universe Domain cannot be an empty string.") 

490 return universe_domain 

491 

492 def _validate_universe_domain(self): 

493 """Validates client's and credentials' universe domains are consistent. 

494 

495 Returns: 

496 bool: True iff the configured universe domain is valid. 

497 

498 Raises: 

499 ValueError: If the configured universe domain is not valid. 

500 """ 

501 

502 # NOTE (b/349488459): universe validation is disabled until further notice. 

503 return True 

504 

505 def _add_cred_info_for_auth_errors( 

506 self, error: core_exceptions.GoogleAPICallError 

507 ) -> None: 

508 """Adds credential info string to error details for 401/403/404 errors. 

509 

510 Args: 

511 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. 

512 """ 

513 if error.code not in [ 

514 HTTPStatus.UNAUTHORIZED, 

515 HTTPStatus.FORBIDDEN, 

516 HTTPStatus.NOT_FOUND, 

517 ]: 

518 return 

519 

520 cred = self._transport._credentials 

521 

522 # get_cred_info is only available in google-auth>=2.35.0 

523 if not hasattr(cred, "get_cred_info"): 

524 return 

525 

526 # ignore the type check since pypy test fails when get_cred_info 

527 # is not available 

528 cred_info = cred.get_cred_info() # type: ignore 

529 if cred_info and hasattr(error._details, "append"): 

530 error._details.append(json.dumps(cred_info)) 

531 

532 @property 

533 def api_endpoint(self): 

534 """Return the API endpoint used by the client instance. 

535 

536 Returns: 

537 str: The API endpoint used by the client instance. 

538 """ 

539 return self._api_endpoint 

540 

541 @property 

542 def universe_domain(self) -> str: 

543 """Return the universe domain used by the client instance. 

544 

545 Returns: 

546 str: The universe domain used by the client instance. 

547 """ 

548 return self._universe_domain 

549 

550 def __init__( 

551 self, 

552 *, 

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

554 transport: Optional[ 

555 Union[ 

556 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] 

557 ] 

558 ] = None, 

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

560 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

561 ) -> None: 

562 """Instantiates the metrics service v2 client. 

563 

564 Args: 

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

566 authorization credentials to attach to requests. These 

567 credentials identify the application to the service; if none 

568 are specified, the client will attempt to ascertain the 

569 credentials from the environment. 

570 transport (Optional[Union[str,MetricsServiceV2Transport,Callable[..., MetricsServiceV2Transport]]]): 

571 The transport to use, or a Callable that constructs and returns a new transport. 

572 If a Callable is given, it will be called with the same set of initialization 

573 arguments as used in the MetricsServiceV2Transport constructor. 

574 If set to None, a transport is chosen automatically. 

575 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

576 Custom options for the client. 

577 

578 1. The ``api_endpoint`` property can be used to override the 

579 default endpoint provided by the client when ``transport`` is 

580 not explicitly provided. Only if this property is not set and 

581 ``transport`` was not explicitly provided, the endpoint is 

582 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

583 variable, which have one of the following values: 

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

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

586 default mTLS endpoint if client certificate is present; this is 

587 the default value). 

588 

589 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

591 to provide a client certificate for mTLS transport. If 

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

593 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

594 set, no client certificate will be used. 

595 

596 3. The ``universe_domain`` property can be used to override the 

597 default "googleapis.com" universe. Note that the ``api_endpoint`` 

598 property still takes precedence; and ``universe_domain`` is 

599 currently not supported for mTLS. 

600 

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

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

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

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

605 your own client library. 

606 

607 Raises: 

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

609 creation failed for any reason. 

610 """ 

611 self._client_options = client_options 

612 if isinstance(self._client_options, dict): 

613 self._client_options = client_options_lib.from_dict(self._client_options) 

614 if self._client_options is None: 

615 self._client_options = client_options_lib.ClientOptions() 

616 self._client_options = cast( 

617 client_options_lib.ClientOptions, self._client_options 

618 ) 

619 

620 universe_domain_opt = getattr(self._client_options, "universe_domain", None) 

621 

622 ( 

623 self._use_client_cert, 

624 self._use_mtls_endpoint, 

625 self._universe_domain_env, 

626 ) = MetricsServiceV2Client._read_environment_variables() 

627 self._client_cert_source = MetricsServiceV2Client._get_client_cert_source( 

628 self._client_options.client_cert_source, self._use_client_cert 

629 ) 

630 self._universe_domain = MetricsServiceV2Client._get_universe_domain( 

631 universe_domain_opt, self._universe_domain_env 

632 ) 

633 self._api_endpoint = None # updated below, depending on `transport` 

634 

635 # Initialize the universe domain validation. 

636 self._is_universe_domain_valid = False 

637 

638 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

639 # Setup logging. 

640 client_logging.initialize_logging() 

641 

642 api_key_value = getattr(self._client_options, "api_key", None) 

643 if api_key_value and credentials: 

644 raise ValueError( 

645 "client_options.api_key and credentials are mutually exclusive" 

646 ) 

647 

648 # Save or instantiate the transport. 

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

650 # instance provides an extensibility point for unusual situations. 

651 transport_provided = isinstance(transport, MetricsServiceV2Transport) 

652 if transport_provided: 

653 # transport is a MetricsServiceV2Transport instance. 

654 if credentials or self._client_options.credentials_file or api_key_value: 

655 raise ValueError( 

656 "When providing a transport instance, " 

657 "provide its credentials directly." 

658 ) 

659 if self._client_options.scopes: 

660 raise ValueError( 

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

662 "directly." 

663 ) 

664 self._transport = cast(MetricsServiceV2Transport, transport) 

665 self._api_endpoint = self._transport.host 

666 

667 self._api_endpoint = ( 

668 self._api_endpoint 

669 or MetricsServiceV2Client._get_api_endpoint( 

670 self._client_options.api_endpoint, 

671 self._client_cert_source, 

672 self._universe_domain, 

673 self._use_mtls_endpoint, 

674 ) 

675 ) 

676 

677 if not transport_provided: 

678 import google.auth._default # type: ignore 

679 

680 if api_key_value and hasattr( 

681 google.auth._default, "get_api_key_credentials" 

682 ): 

683 credentials = google.auth._default.get_api_key_credentials( 

684 api_key_value 

685 ) 

686 

687 transport_init: Union[ 

688 Type[MetricsServiceV2Transport], 

689 Callable[..., MetricsServiceV2Transport], 

690 ] = ( 

691 MetricsServiceV2Client.get_transport_class(transport) 

692 if isinstance(transport, str) or transport is None 

693 else cast(Callable[..., MetricsServiceV2Transport], transport) 

694 ) 

695 # initialize with the provided callable or the passed in class 

696 self._transport = transport_init( 

697 credentials=credentials, 

698 credentials_file=self._client_options.credentials_file, 

699 host=self._api_endpoint, 

700 scopes=self._client_options.scopes, 

701 client_cert_source_for_mtls=self._client_cert_source, 

702 quota_project_id=self._client_options.quota_project_id, 

703 client_info=client_info, 

704 always_use_jwt_access=True, 

705 api_audience=self._client_options.api_audience, 

706 ) 

707 

708 if "async" not in str(self._transport): 

709 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

710 std_logging.DEBUG 

711 ): # pragma: NO COVER 

712 _LOGGER.debug( 

713 "Created client `google.logging_v2.MetricsServiceV2Client`.", 

714 extra={ 

715 "serviceName": "google.logging.v2.MetricsServiceV2", 

716 "universeDomain": getattr( 

717 self._transport._credentials, "universe_domain", "" 

718 ), 

719 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", 

720 "credentialsInfo": getattr( 

721 self.transport._credentials, "get_cred_info", lambda: None 

722 )(), 

723 } 

724 if hasattr(self._transport, "_credentials") 

725 else { 

726 "serviceName": "google.logging.v2.MetricsServiceV2", 

727 "credentialsType": None, 

728 }, 

729 ) 

730 

731 def list_log_metrics( 

732 self, 

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

734 *, 

735 parent: Optional[str] = None, 

736 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

738 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

739 ) -> pagers.ListLogMetricsPager: 

740 r"""Lists logs-based metrics. 

741 

742 .. code-block:: python 

743 

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

745 # code template only. 

746 # It will require modifications to work: 

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

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

749 # client as shown in: 

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

751 from google.cloud import logging_v2 

752 

753 def sample_list_log_metrics(): 

754 # Create a client 

755 client = logging_v2.MetricsServiceV2Client() 

756 

757 # Initialize request argument(s) 

758 request = logging_v2.ListLogMetricsRequest( 

759 parent="parent_value", 

760 ) 

761 

762 # Make the request 

763 page_result = client.list_log_metrics(request=request) 

764 

765 # Handle the response 

766 for response in page_result: 

767 print(response) 

768 

769 Args: 

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

771 The request object. The parameters to ListLogMetrics. 

772 parent (str): 

773 Required. The name of the project containing the 

774 metrics: 

775 

776 :: 

777 

778 "projects/[PROJECT_ID]" 

779 

780 This corresponds to the ``parent`` field 

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

782 should not be set. 

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

784 should be retried. 

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

786 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

787 sent along with the request as metadata. Normally, each value must be of type `str`, 

788 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

789 be of type `bytes`. 

790 

791 Returns: 

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

793 Result returned from ListLogMetrics. 

794 

795 Iterating over this object will yield 

796 results and resolve additional pages 

797 automatically. 

798 

799 """ 

800 # Create or coerce a protobuf request object. 

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

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

803 flattened_params = [parent] 

804 has_flattened_params = ( 

805 len([param for param in flattened_params if param is not None]) > 0 

806 ) 

807 if request is not None and has_flattened_params: 

808 raise ValueError( 

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

810 "the individual field arguments should be set." 

811 ) 

812 

813 # - Use the request object if provided (there's no risk of modifying the input as 

814 # there are no flattened fields), or create one. 

815 if not isinstance(request, logging_metrics.ListLogMetricsRequest): 

816 request = logging_metrics.ListLogMetricsRequest(request) 

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

818 # request, apply these. 

819 if parent is not None: 

820 request.parent = parent 

821 

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

823 # and friendly error handling. 

824 rpc = self._transport._wrapped_methods[self._transport.list_log_metrics] 

825 

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

827 # add these here. 

828 metadata = tuple(metadata) + ( 

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

830 ) 

831 

832 # Validate the universe domain. 

833 self._validate_universe_domain() 

834 

835 # Send the request. 

836 response = rpc( 

837 request, 

838 retry=retry, 

839 timeout=timeout, 

840 metadata=metadata, 

841 ) 

842 

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

844 # an `__iter__` convenience method. 

845 response = pagers.ListLogMetricsPager( 

846 method=rpc, 

847 request=request, 

848 response=response, 

849 retry=retry, 

850 timeout=timeout, 

851 metadata=metadata, 

852 ) 

853 

854 # Done; return the response. 

855 return response 

856 

857 def get_log_metric( 

858 self, 

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

860 *, 

861 metric_name: Optional[str] = None, 

862 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

864 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

865 ) -> logging_metrics.LogMetric: 

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

867 

868 .. code-block:: python 

869 

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

871 # code template only. 

872 # It will require modifications to work: 

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

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

875 # client as shown in: 

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

877 from google.cloud import logging_v2 

878 

879 def sample_get_log_metric(): 

880 # Create a client 

881 client = logging_v2.MetricsServiceV2Client() 

882 

883 # Initialize request argument(s) 

884 request = logging_v2.GetLogMetricRequest( 

885 metric_name="metric_name_value", 

886 ) 

887 

888 # Make the request 

889 response = client.get_log_metric(request=request) 

890 

891 # Handle the response 

892 print(response) 

893 

894 Args: 

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

896 The request object. The parameters to GetLogMetric. 

897 metric_name (str): 

898 Required. The resource name of the desired metric: 

899 

900 :: 

901 

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

903 

904 This corresponds to the ``metric_name`` field 

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

906 should not be set. 

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

908 should be retried. 

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

910 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

911 sent along with the request as metadata. Normally, each value must be of type `str`, 

912 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

913 be of type `bytes`. 

914 

915 Returns: 

916 google.cloud.logging_v2.types.LogMetric: 

917 Describes a logs-based metric. The 

918 value of the metric is the number of log 

919 entries that match a logs filter in a 

920 given time interval. 

921 

922 Logs-based metrics can also be used to 

923 extract values from logs and create a 

924 distribution of the values. The 

925 distribution records the statistics of 

926 the extracted values along with an 

927 optional histogram of the values as 

928 specified by the bucket options. 

929 

930 """ 

931 # Create or coerce a protobuf request object. 

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

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

934 flattened_params = [metric_name] 

935 has_flattened_params = ( 

936 len([param for param in flattened_params if param is not None]) > 0 

937 ) 

938 if request is not None and has_flattened_params: 

939 raise ValueError( 

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

941 "the individual field arguments should be set." 

942 ) 

943 

944 # - Use the request object if provided (there's no risk of modifying the input as 

945 # there are no flattened fields), or create one. 

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

947 request = logging_metrics.GetLogMetricRequest(request) 

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

949 # request, apply these. 

950 if metric_name is not None: 

951 request.metric_name = metric_name 

952 

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

954 # and friendly error handling. 

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

956 

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

958 # add these here. 

959 metadata = tuple(metadata) + ( 

960 gapic_v1.routing_header.to_grpc_metadata( 

961 (("metric_name", request.metric_name),) 

962 ), 

963 ) 

964 

965 # Validate the universe domain. 

966 self._validate_universe_domain() 

967 

968 # Send the request. 

969 response = rpc( 

970 request, 

971 retry=retry, 

972 timeout=timeout, 

973 metadata=metadata, 

974 ) 

975 

976 # Done; return the response. 

977 return response 

978 

979 def create_log_metric( 

980 self, 

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

982 *, 

983 parent: Optional[str] = None, 

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

985 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

987 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

988 ) -> logging_metrics.LogMetric: 

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

990 

991 .. code-block:: python 

992 

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

994 # code template only. 

995 # It will require modifications to work: 

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

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

998 # client as shown in: 

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

1000 from google.cloud import logging_v2 

1001 

1002 def sample_create_log_metric(): 

1003 # Create a client 

1004 client = logging_v2.MetricsServiceV2Client() 

1005 

1006 # Initialize request argument(s) 

1007 metric = logging_v2.LogMetric() 

1008 metric.name = "name_value" 

1009 metric.filter = "filter_value" 

1010 

1011 request = logging_v2.CreateLogMetricRequest( 

1012 parent="parent_value", 

1013 metric=metric, 

1014 ) 

1015 

1016 # Make the request 

1017 response = client.create_log_metric(request=request) 

1018 

1019 # Handle the response 

1020 print(response) 

1021 

1022 Args: 

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

1024 The request object. The parameters to CreateLogMetric. 

1025 parent (str): 

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

1027 create the metric: 

1028 

1029 :: 

1030 

1031 "projects/[PROJECT_ID]" 

1032 

1033 The new metric must be provided in the request. 

1034 

1035 This corresponds to the ``parent`` field 

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

1037 should not be set. 

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

1039 Required. The new logs-based metric, 

1040 which must not have an identifier that 

1041 already exists. 

1042 

1043 This corresponds to the ``metric`` field 

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

1045 should not be set. 

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

1047 should be retried. 

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

1049 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1050 sent along with the request as metadata. Normally, each value must be of type `str`, 

1051 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1052 be of type `bytes`. 

1053 

1054 Returns: 

1055 google.cloud.logging_v2.types.LogMetric: 

1056 Describes a logs-based metric. The 

1057 value of the metric is the number of log 

1058 entries that match a logs filter in a 

1059 given time interval. 

1060 

1061 Logs-based metrics can also be used to 

1062 extract values from logs and create a 

1063 distribution of the values. The 

1064 distribution records the statistics of 

1065 the extracted values along with an 

1066 optional histogram of the values as 

1067 specified by the bucket options. 

1068 

1069 """ 

1070 # Create or coerce a protobuf request object. 

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

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

1073 flattened_params = [parent, metric] 

1074 has_flattened_params = ( 

1075 len([param for param in flattened_params if param is not None]) > 0 

1076 ) 

1077 if request is not None and has_flattened_params: 

1078 raise ValueError( 

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

1080 "the individual field arguments should be set." 

1081 ) 

1082 

1083 # - Use the request object if provided (there's no risk of modifying the input as 

1084 # there are no flattened fields), or create one. 

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

1086 request = logging_metrics.CreateLogMetricRequest(request) 

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

1088 # request, apply these. 

1089 if parent is not None: 

1090 request.parent = parent 

1091 if metric is not None: 

1092 request.metric = metric 

1093 

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

1095 # and friendly error handling. 

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

1097 

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

1099 # add these here. 

1100 metadata = tuple(metadata) + ( 

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

1102 ) 

1103 

1104 # Validate the universe domain. 

1105 self._validate_universe_domain() 

1106 

1107 # Send the request. 

1108 response = rpc( 

1109 request, 

1110 retry=retry, 

1111 timeout=timeout, 

1112 metadata=metadata, 

1113 ) 

1114 

1115 # Done; return the response. 

1116 return response 

1117 

1118 def update_log_metric( 

1119 self, 

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

1121 *, 

1122 metric_name: Optional[str] = None, 

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

1124 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1126 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1127 ) -> logging_metrics.LogMetric: 

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

1129 

1130 .. code-block:: python 

1131 

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

1133 # code template only. 

1134 # It will require modifications to work: 

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

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

1137 # client as shown in: 

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

1139 from google.cloud import logging_v2 

1140 

1141 def sample_update_log_metric(): 

1142 # Create a client 

1143 client = logging_v2.MetricsServiceV2Client() 

1144 

1145 # Initialize request argument(s) 

1146 metric = logging_v2.LogMetric() 

1147 metric.name = "name_value" 

1148 metric.filter = "filter_value" 

1149 

1150 request = logging_v2.UpdateLogMetricRequest( 

1151 metric_name="metric_name_value", 

1152 metric=metric, 

1153 ) 

1154 

1155 # Make the request 

1156 response = client.update_log_metric(request=request) 

1157 

1158 # Handle the response 

1159 print(response) 

1160 

1161 Args: 

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

1163 The request object. The parameters to UpdateLogMetric. 

1164 metric_name (str): 

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

1166 

1167 :: 

1168 

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

1170 

1171 The updated metric must be provided in the request and 

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

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

1174 new metric is created. 

1175 

1176 This corresponds to the ``metric_name`` field 

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

1178 should not be set. 

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

1180 Required. The updated metric. 

1181 This corresponds to the ``metric`` field 

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

1183 should not be set. 

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

1185 should be retried. 

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

1187 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1188 sent along with the request as metadata. Normally, each value must be of type `str`, 

1189 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1190 be of type `bytes`. 

1191 

1192 Returns: 

1193 google.cloud.logging_v2.types.LogMetric: 

1194 Describes a logs-based metric. The 

1195 value of the metric is the number of log 

1196 entries that match a logs filter in a 

1197 given time interval. 

1198 

1199 Logs-based metrics can also be used to 

1200 extract values from logs and create a 

1201 distribution of the values. The 

1202 distribution records the statistics of 

1203 the extracted values along with an 

1204 optional histogram of the values as 

1205 specified by the bucket options. 

1206 

1207 """ 

1208 # Create or coerce a protobuf request object. 

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

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

1211 flattened_params = [metric_name, metric] 

1212 has_flattened_params = ( 

1213 len([param for param in flattened_params if param is not None]) > 0 

1214 ) 

1215 if request is not None and has_flattened_params: 

1216 raise ValueError( 

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

1218 "the individual field arguments should be set." 

1219 ) 

1220 

1221 # - Use the request object if provided (there's no risk of modifying the input as 

1222 # there are no flattened fields), or create one. 

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

1224 request = logging_metrics.UpdateLogMetricRequest(request) 

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

1226 # request, apply these. 

1227 if metric_name is not None: 

1228 request.metric_name = metric_name 

1229 if metric is not None: 

1230 request.metric = metric 

1231 

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

1233 # and friendly error handling. 

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

1235 

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

1237 # add these here. 

1238 metadata = tuple(metadata) + ( 

1239 gapic_v1.routing_header.to_grpc_metadata( 

1240 (("metric_name", request.metric_name),) 

1241 ), 

1242 ) 

1243 

1244 # Validate the universe domain. 

1245 self._validate_universe_domain() 

1246 

1247 # Send the request. 

1248 response = rpc( 

1249 request, 

1250 retry=retry, 

1251 timeout=timeout, 

1252 metadata=metadata, 

1253 ) 

1254 

1255 # Done; return the response. 

1256 return response 

1257 

1258 def delete_log_metric( 

1259 self, 

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

1261 *, 

1262 metric_name: Optional[str] = None, 

1263 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1265 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1266 ) -> None: 

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

1268 

1269 .. code-block:: python 

1270 

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

1272 # code template only. 

1273 # It will require modifications to work: 

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

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

1276 # client as shown in: 

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

1278 from google.cloud import logging_v2 

1279 

1280 def sample_delete_log_metric(): 

1281 # Create a client 

1282 client = logging_v2.MetricsServiceV2Client() 

1283 

1284 # Initialize request argument(s) 

1285 request = logging_v2.DeleteLogMetricRequest( 

1286 metric_name="metric_name_value", 

1287 ) 

1288 

1289 # Make the request 

1290 client.delete_log_metric(request=request) 

1291 

1292 Args: 

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

1294 The request object. The parameters to DeleteLogMetric. 

1295 metric_name (str): 

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

1297 

1298 :: 

1299 

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

1301 

1302 This corresponds to the ``metric_name`` field 

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

1304 should not be set. 

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

1306 should be retried. 

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

1308 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1309 sent along with the request as metadata. Normally, each value must be of type `str`, 

1310 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1311 be of type `bytes`. 

1312 """ 

1313 # Create or coerce a protobuf request object. 

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

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

1316 flattened_params = [metric_name] 

1317 has_flattened_params = ( 

1318 len([param for param in flattened_params if param is not None]) > 0 

1319 ) 

1320 if request is not None and has_flattened_params: 

1321 raise ValueError( 

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

1323 "the individual field arguments should be set." 

1324 ) 

1325 

1326 # - Use the request object if provided (there's no risk of modifying the input as 

1327 # there are no flattened fields), or create one. 

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

1329 request = logging_metrics.DeleteLogMetricRequest(request) 

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

1331 # request, apply these. 

1332 if metric_name is not None: 

1333 request.metric_name = metric_name 

1334 

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

1336 # and friendly error handling. 

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

1338 

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

1340 # add these here. 

1341 metadata = tuple(metadata) + ( 

1342 gapic_v1.routing_header.to_grpc_metadata( 

1343 (("metric_name", request.metric_name),) 

1344 ), 

1345 ) 

1346 

1347 # Validate the universe domain. 

1348 self._validate_universe_domain() 

1349 

1350 # Send the request. 

1351 rpc( 

1352 request, 

1353 retry=retry, 

1354 timeout=timeout, 

1355 metadata=metadata, 

1356 ) 

1357 

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

1359 return self 

1360 

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

1362 """Releases underlying transport's resources. 

1363 

1364 .. warning:: 

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

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

1367 and may cause errors in other clients! 

1368 """ 

1369 self.transport.close() 

1370 

1371 def list_operations( 

1372 self, 

1373 request: Optional[operations_pb2.ListOperationsRequest] = None, 

1374 *, 

1375 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1377 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1378 ) -> operations_pb2.ListOperationsResponse: 

1379 r"""Lists operations that match the specified filter in the request. 

1380 

1381 Args: 

1382 request (:class:`~.operations_pb2.ListOperationsRequest`): 

1383 The request object. Request message for 

1384 `ListOperations` method. 

1385 retry (google.api_core.retry.Retry): Designation of what errors, 

1386 if any, should be retried. 

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

1388 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1389 sent along with the request as metadata. Normally, each value must be of type `str`, 

1390 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1391 be of type `bytes`. 

1392 Returns: 

1393 ~.operations_pb2.ListOperationsResponse: 

1394 Response message for ``ListOperations`` method. 

1395 """ 

1396 # Create or coerce a protobuf request object. 

1397 # The request isn't a proto-plus wrapped type, 

1398 # so it must be constructed via keyword expansion. 

1399 if isinstance(request, dict): 

1400 request = operations_pb2.ListOperationsRequest(**request) 

1401 

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

1403 # and friendly error handling. 

1404 rpc = self._transport._wrapped_methods[self._transport.list_operations] 

1405 

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

1407 # add these here. 

1408 metadata = tuple(metadata) + ( 

1409 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1410 ) 

1411 

1412 # Validate the universe domain. 

1413 self._validate_universe_domain() 

1414 

1415 try: 

1416 # Send the request. 

1417 response = rpc( 

1418 request, 

1419 retry=retry, 

1420 timeout=timeout, 

1421 metadata=metadata, 

1422 ) 

1423 

1424 # Done; return the response. 

1425 return response 

1426 except core_exceptions.GoogleAPICallError as e: 

1427 self._add_cred_info_for_auth_errors(e) 

1428 raise e 

1429 

1430 def get_operation( 

1431 self, 

1432 request: Optional[operations_pb2.GetOperationRequest] = None, 

1433 *, 

1434 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1436 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1437 ) -> operations_pb2.Operation: 

1438 r"""Gets the latest state of a long-running operation. 

1439 

1440 Args: 

1441 request (:class:`~.operations_pb2.GetOperationRequest`): 

1442 The request object. Request message for 

1443 `GetOperation` method. 

1444 retry (google.api_core.retry.Retry): Designation of what errors, 

1445 if any, should be retried. 

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

1447 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1448 sent along with the request as metadata. Normally, each value must be of type `str`, 

1449 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1450 be of type `bytes`. 

1451 Returns: 

1452 ~.operations_pb2.Operation: 

1453 An ``Operation`` object. 

1454 """ 

1455 # Create or coerce a protobuf request object. 

1456 # The request isn't a proto-plus wrapped type, 

1457 # so it must be constructed via keyword expansion. 

1458 if isinstance(request, dict): 

1459 request = operations_pb2.GetOperationRequest(**request) 

1460 

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

1462 # and friendly error handling. 

1463 rpc = self._transport._wrapped_methods[self._transport.get_operation] 

1464 

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

1466 # add these here. 

1467 metadata = tuple(metadata) + ( 

1468 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1469 ) 

1470 

1471 # Validate the universe domain. 

1472 self._validate_universe_domain() 

1473 

1474 try: 

1475 # Send the request. 

1476 response = rpc( 

1477 request, 

1478 retry=retry, 

1479 timeout=timeout, 

1480 metadata=metadata, 

1481 ) 

1482 

1483 # Done; return the response. 

1484 return response 

1485 except core_exceptions.GoogleAPICallError as e: 

1486 self._add_cred_info_for_auth_errors(e) 

1487 raise e 

1488 

1489 def cancel_operation( 

1490 self, 

1491 request: Optional[operations_pb2.CancelOperationRequest] = None, 

1492 *, 

1493 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1495 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1496 ) -> None: 

1497 r"""Starts asynchronous cancellation on a long-running operation. 

1498 

1499 The server makes a best effort to cancel the operation, but success 

1500 is not guaranteed. If the server doesn't support this method, it returns 

1501 `google.rpc.Code.UNIMPLEMENTED`. 

1502 

1503 Args: 

1504 request (:class:`~.operations_pb2.CancelOperationRequest`): 

1505 The request object. Request message for 

1506 `CancelOperation` method. 

1507 retry (google.api_core.retry.Retry): Designation of what errors, 

1508 if any, should be retried. 

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

1510 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1511 sent along with the request as metadata. Normally, each value must be of type `str`, 

1512 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1513 be of type `bytes`. 

1514 Returns: 

1515 None 

1516 """ 

1517 # Create or coerce a protobuf request object. 

1518 # The request isn't a proto-plus wrapped type, 

1519 # so it must be constructed via keyword expansion. 

1520 if isinstance(request, dict): 

1521 request = operations_pb2.CancelOperationRequest(**request) 

1522 

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

1524 # and friendly error handling. 

1525 rpc = self._transport._wrapped_methods[self._transport.cancel_operation] 

1526 

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

1528 # add these here. 

1529 metadata = tuple(metadata) + ( 

1530 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

1531 ) 

1532 

1533 # Validate the universe domain. 

1534 self._validate_universe_domain() 

1535 

1536 # Send the request. 

1537 rpc( 

1538 request, 

1539 retry=retry, 

1540 timeout=timeout, 

1541 metadata=metadata, 

1542 ) 

1543 

1544 

1545DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1546 gapic_version=package_version.__version__ 

1547) 

1548 

1549if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

1550 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1551 

1552__all__ = ("MetricsServiceV2Client",)