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

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

171 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# 

16import logging as std_logging 

17from collections import OrderedDict 

18import re 

19from typing import ( 

20 Dict, 

21 Callable, 

22 Mapping, 

23 MutableMapping, 

24 MutableSequence, 

25 Optional, 

26 Sequence, 

27 Tuple, 

28 Type, 

29 Union, 

30) 

31import uuid 

32 

33from google.cloud.logging_v2 import gapic_version as package_version 

34 

35from google.api_core.client_options import ClientOptions 

36from google.api_core import exceptions as core_exceptions 

37from google.api_core import gapic_v1 

38from google.api_core import retry_async as retries 

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

40from google.oauth2 import service_account # type: ignore 

41import google.protobuf 

42 

43 

44try: 

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

46except AttributeError: # pragma: NO COVER 

47 OptionalRetry = Union[retries.AsyncRetry, object, None] # 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.longrunning import operations_pb2 # type: ignore 

54from google.protobuf import timestamp_pb2 # type: ignore 

55from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO 

56from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport 

57from .client import MetricsServiceV2Client 

58 

59try: 

60 from google.api_core import client_logging # type: ignore 

61 

62 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

63except ImportError: # pragma: NO COVER 

64 CLIENT_LOGGING_SUPPORTED = False 

65 

66_LOGGER = std_logging.getLogger(__name__) 

67 

68 

69class MetricsServiceV2AsyncClient: 

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

71 

72 _client: MetricsServiceV2Client 

73 

74 # Copy defaults from the synchronous client for use here. 

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

76 DEFAULT_ENDPOINT = MetricsServiceV2Client.DEFAULT_ENDPOINT 

77 DEFAULT_MTLS_ENDPOINT = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT 

78 _DEFAULT_ENDPOINT_TEMPLATE = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE 

79 _DEFAULT_UNIVERSE = MetricsServiceV2Client._DEFAULT_UNIVERSE 

80 

81 log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path) 

82 parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path) 

83 common_billing_account_path = staticmethod( 

84 MetricsServiceV2Client.common_billing_account_path 

85 ) 

86 parse_common_billing_account_path = staticmethod( 

87 MetricsServiceV2Client.parse_common_billing_account_path 

88 ) 

89 common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path) 

90 parse_common_folder_path = staticmethod( 

91 MetricsServiceV2Client.parse_common_folder_path 

92 ) 

93 common_organization_path = staticmethod( 

94 MetricsServiceV2Client.common_organization_path 

95 ) 

96 parse_common_organization_path = staticmethod( 

97 MetricsServiceV2Client.parse_common_organization_path 

98 ) 

99 common_project_path = staticmethod(MetricsServiceV2Client.common_project_path) 

100 parse_common_project_path = staticmethod( 

101 MetricsServiceV2Client.parse_common_project_path 

102 ) 

103 common_location_path = staticmethod(MetricsServiceV2Client.common_location_path) 

104 parse_common_location_path = staticmethod( 

105 MetricsServiceV2Client.parse_common_location_path 

106 ) 

107 

108 @classmethod 

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

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

111 info. 

112 

113 Args: 

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

115 args: Additional arguments to pass to the constructor. 

116 kwargs: Additional arguments to pass to the constructor. 

117 

118 Returns: 

119 MetricsServiceV2AsyncClient: The constructed client. 

120 """ 

121 return MetricsServiceV2Client.from_service_account_info.__func__(MetricsServiceV2AsyncClient, info, *args, **kwargs) # type: ignore 

122 

123 @classmethod 

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

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

126 file. 

127 

128 Args: 

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

130 file. 

131 args: Additional arguments to pass to the constructor. 

132 kwargs: Additional arguments to pass to the constructor. 

133 

134 Returns: 

135 MetricsServiceV2AsyncClient: The constructed client. 

136 """ 

137 return MetricsServiceV2Client.from_service_account_file.__func__(MetricsServiceV2AsyncClient, filename, *args, **kwargs) # type: ignore 

138 

139 from_service_account_json = from_service_account_file 

140 

141 @classmethod 

142 def get_mtls_endpoint_and_cert_source( 

143 cls, client_options: Optional[ClientOptions] = None 

144 ): 

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

146 

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

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

149 client cert source is None. 

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

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

152 source is None. 

153 

154 The API endpoint is determined in the following order: 

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

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

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

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

159 use the default API endpoint. 

160 

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

162 

163 Args: 

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

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

166 in this method. 

167 

168 Returns: 

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

170 client cert source to use. 

171 

172 Raises: 

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

174 """ 

175 return MetricsServiceV2Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore 

176 

177 @property 

178 def transport(self) -> MetricsServiceV2Transport: 

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

180 

181 Returns: 

182 MetricsServiceV2Transport: The transport used by the client instance. 

183 """ 

184 return self._client.transport 

185 

186 @property 

187 def api_endpoint(self): 

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

189 

190 Returns: 

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

192 """ 

193 return self._client._api_endpoint 

194 

195 @property 

196 def universe_domain(self) -> str: 

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

198 

199 Returns: 

200 str: The universe domain used 

201 by the client instance. 

202 """ 

203 return self._client._universe_domain 

204 

205 get_transport_class = MetricsServiceV2Client.get_transport_class 

206 

207 def __init__( 

208 self, 

209 *, 

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

211 transport: Optional[ 

212 Union[ 

213 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] 

214 ] 

215 ] = "grpc_asyncio", 

216 client_options: Optional[ClientOptions] = None, 

217 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

218 ) -> None: 

219 """Instantiates the metrics service v2 async client. 

220 

221 Args: 

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

223 authorization credentials to attach to requests. These 

224 credentials identify the application to the service; if none 

225 are specified, the client will attempt to ascertain the 

226 credentials from the environment. 

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

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

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

230 arguments as used in the MetricsServiceV2Transport constructor. 

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

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

233 Custom options for the client. 

234 

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

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

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

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

239 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

240 variable, which have one of the following values: 

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

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

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

244 the default value). 

245 

246 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

248 to provide a client certificate for mTLS transport. If 

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

250 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

251 set, no client certificate will be used. 

252 

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

254 default "googleapis.com" universe. Note that ``api_endpoint`` 

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

256 currently not supported for mTLS. 

257 

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

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

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

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

262 your own client library. 

263 

264 Raises: 

265 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 

266 creation failed for any reason. 

267 """ 

268 self._client = MetricsServiceV2Client( 

269 credentials=credentials, 

270 transport=transport, 

271 client_options=client_options, 

272 client_info=client_info, 

273 ) 

274 

275 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

276 std_logging.DEBUG 

277 ): # pragma: NO COVER 

278 _LOGGER.debug( 

279 "Created client `google.logging_v2.MetricsServiceV2AsyncClient`.", 

280 extra={ 

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

282 "universeDomain": getattr( 

283 self._client._transport._credentials, "universe_domain", "" 

284 ), 

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

286 "credentialsInfo": getattr( 

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

288 )(), 

289 } 

290 if hasattr(self._client._transport, "_credentials") 

291 else { 

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

293 "credentialsType": None, 

294 }, 

295 ) 

296 

297 async def list_log_metrics( 

298 self, 

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

300 *, 

301 parent: Optional[str] = None, 

302 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

305 ) -> pagers.ListLogMetricsAsyncPager: 

306 r"""Lists logs-based metrics. 

307 

308 .. code-block:: python 

309 

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

311 # code template only. 

312 # It will require modifications to work: 

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

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

315 # client as shown in: 

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

317 from google.cloud import logging_v2 

318 

319 async def sample_list_log_metrics(): 

320 # Create a client 

321 client = logging_v2.MetricsServiceV2AsyncClient() 

322 

323 # Initialize request argument(s) 

324 request = logging_v2.ListLogMetricsRequest( 

325 parent="parent_value", 

326 ) 

327 

328 # Make the request 

329 page_result = client.list_log_metrics(request=request) 

330 

331 # Handle the response 

332 async for response in page_result: 

333 print(response) 

334 

335 Args: 

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

337 The request object. The parameters to ListLogMetrics. 

338 parent (:class:`str`): 

339 Required. The name of the project containing the 

340 metrics: 

341 

342 :: 

343 

344 "projects/[PROJECT_ID]" 

345 

346 This corresponds to the ``parent`` field 

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

348 should not be set. 

349 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

350 should be retried. 

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

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

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

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

355 be of type `bytes`. 

356 

357 Returns: 

358 google.cloud.logging_v2.services.metrics_service_v2.pagers.ListLogMetricsAsyncPager: 

359 Result returned from ListLogMetrics. 

360 

361 Iterating over this object will yield 

362 results and resolve additional pages 

363 automatically. 

364 

365 """ 

366 # Create or coerce a protobuf request object. 

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

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

369 flattened_params = [parent] 

370 has_flattened_params = ( 

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

372 ) 

373 if request is not None and has_flattened_params: 

374 raise ValueError( 

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

376 "the individual field arguments should be set." 

377 ) 

378 

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

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

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

382 request = logging_metrics.ListLogMetricsRequest(request) 

383 

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

385 # request, apply these. 

386 if parent is not None: 

387 request.parent = parent 

388 

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

390 # and friendly error handling. 

391 rpc = self._client._transport._wrapped_methods[ 

392 self._client._transport.list_log_metrics 

393 ] 

394 

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

396 # add these here. 

397 metadata = tuple(metadata) + ( 

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

399 ) 

400 

401 # Validate the universe domain. 

402 self._client._validate_universe_domain() 

403 

404 # Send the request. 

405 response = await rpc( 

406 request, 

407 retry=retry, 

408 timeout=timeout, 

409 metadata=metadata, 

410 ) 

411 

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

413 # an `__aiter__` convenience method. 

414 response = pagers.ListLogMetricsAsyncPager( 

415 method=rpc, 

416 request=request, 

417 response=response, 

418 retry=retry, 

419 timeout=timeout, 

420 metadata=metadata, 

421 ) 

422 

423 # Done; return the response. 

424 return response 

425 

426 async def get_log_metric( 

427 self, 

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

429 *, 

430 metric_name: Optional[str] = None, 

431 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

434 ) -> logging_metrics.LogMetric: 

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

436 

437 .. code-block:: python 

438 

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

440 # code template only. 

441 # It will require modifications to work: 

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

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

444 # client as shown in: 

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

446 from google.cloud import logging_v2 

447 

448 async def sample_get_log_metric(): 

449 # Create a client 

450 client = logging_v2.MetricsServiceV2AsyncClient() 

451 

452 # Initialize request argument(s) 

453 request = logging_v2.GetLogMetricRequest( 

454 metric_name="metric_name_value", 

455 ) 

456 

457 # Make the request 

458 response = await client.get_log_metric(request=request) 

459 

460 # Handle the response 

461 print(response) 

462 

463 Args: 

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

465 The request object. The parameters to GetLogMetric. 

466 metric_name (:class:`str`): 

467 Required. The resource name of the desired metric: 

468 

469 :: 

470 

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

472 

473 This corresponds to the ``metric_name`` field 

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

475 should not be set. 

476 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

477 should be retried. 

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

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

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

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

482 be of type `bytes`. 

483 

484 Returns: 

485 google.cloud.logging_v2.types.LogMetric: 

486 Describes a logs-based metric. The 

487 value of the metric is the number of log 

488 entries that match a logs filter in a 

489 given time interval. 

490 

491 Logs-based metrics can also be used to 

492 extract values from logs and create a 

493 distribution of the values. The 

494 distribution records the statistics of 

495 the extracted values along with an 

496 optional histogram of the values as 

497 specified by the bucket options. 

498 

499 """ 

500 # Create or coerce a protobuf request object. 

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

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

503 flattened_params = [metric_name] 

504 has_flattened_params = ( 

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

506 ) 

507 if request is not None and has_flattened_params: 

508 raise ValueError( 

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

510 "the individual field arguments should be set." 

511 ) 

512 

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

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

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

516 request = logging_metrics.GetLogMetricRequest(request) 

517 

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

519 # request, apply these. 

520 if metric_name is not None: 

521 request.metric_name = metric_name 

522 

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

524 # and friendly error handling. 

525 rpc = self._client._transport._wrapped_methods[ 

526 self._client._transport.get_log_metric 

527 ] 

528 

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

530 # add these here. 

531 metadata = tuple(metadata) + ( 

532 gapic_v1.routing_header.to_grpc_metadata( 

533 (("metric_name", request.metric_name),) 

534 ), 

535 ) 

536 

537 # Validate the universe domain. 

538 self._client._validate_universe_domain() 

539 

540 # Send the request. 

541 response = await rpc( 

542 request, 

543 retry=retry, 

544 timeout=timeout, 

545 metadata=metadata, 

546 ) 

547 

548 # Done; return the response. 

549 return response 

550 

551 async def create_log_metric( 

552 self, 

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

554 *, 

555 parent: Optional[str] = None, 

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

557 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

560 ) -> logging_metrics.LogMetric: 

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

562 

563 .. code-block:: python 

564 

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

566 # code template only. 

567 # It will require modifications to work: 

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

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

570 # client as shown in: 

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

572 from google.cloud import logging_v2 

573 

574 async def sample_create_log_metric(): 

575 # Create a client 

576 client = logging_v2.MetricsServiceV2AsyncClient() 

577 

578 # Initialize request argument(s) 

579 metric = logging_v2.LogMetric() 

580 metric.name = "name_value" 

581 metric.filter = "filter_value" 

582 

583 request = logging_v2.CreateLogMetricRequest( 

584 parent="parent_value", 

585 metric=metric, 

586 ) 

587 

588 # Make the request 

589 response = await client.create_log_metric(request=request) 

590 

591 # Handle the response 

592 print(response) 

593 

594 Args: 

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

596 The request object. The parameters to CreateLogMetric. 

597 parent (:class:`str`): 

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

599 create the metric: 

600 

601 :: 

602 

603 "projects/[PROJECT_ID]" 

604 

605 The new metric must be provided in the request. 

606 

607 This corresponds to the ``parent`` field 

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

609 should not be set. 

610 metric (:class:`google.cloud.logging_v2.types.LogMetric`): 

611 Required. The new logs-based metric, 

612 which must not have an identifier that 

613 already exists. 

614 

615 This corresponds to the ``metric`` field 

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

617 should not be set. 

618 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

619 should be retried. 

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

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

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

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

624 be of type `bytes`. 

625 

626 Returns: 

627 google.cloud.logging_v2.types.LogMetric: 

628 Describes a logs-based metric. The 

629 value of the metric is the number of log 

630 entries that match a logs filter in a 

631 given time interval. 

632 

633 Logs-based metrics can also be used to 

634 extract values from logs and create a 

635 distribution of the values. The 

636 distribution records the statistics of 

637 the extracted values along with an 

638 optional histogram of the values as 

639 specified by the bucket options. 

640 

641 """ 

642 # Create or coerce a protobuf request object. 

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

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

645 flattened_params = [parent, metric] 

646 has_flattened_params = ( 

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

648 ) 

649 if request is not None and has_flattened_params: 

650 raise ValueError( 

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

652 "the individual field arguments should be set." 

653 ) 

654 

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

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

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

658 request = logging_metrics.CreateLogMetricRequest(request) 

659 

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

661 # request, apply these. 

662 if parent is not None: 

663 request.parent = parent 

664 if metric is not None: 

665 request.metric = metric 

666 

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

668 # and friendly error handling. 

669 rpc = self._client._transport._wrapped_methods[ 

670 self._client._transport.create_log_metric 

671 ] 

672 

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

674 # add these here. 

675 metadata = tuple(metadata) + ( 

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

677 ) 

678 

679 # Validate the universe domain. 

680 self._client._validate_universe_domain() 

681 

682 # Send the request. 

683 response = await rpc( 

684 request, 

685 retry=retry, 

686 timeout=timeout, 

687 metadata=metadata, 

688 ) 

689 

690 # Done; return the response. 

691 return response 

692 

693 async def update_log_metric( 

694 self, 

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

696 *, 

697 metric_name: Optional[str] = None, 

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

699 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

702 ) -> logging_metrics.LogMetric: 

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

704 

705 .. code-block:: python 

706 

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

708 # code template only. 

709 # It will require modifications to work: 

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

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

712 # client as shown in: 

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

714 from google.cloud import logging_v2 

715 

716 async def sample_update_log_metric(): 

717 # Create a client 

718 client = logging_v2.MetricsServiceV2AsyncClient() 

719 

720 # Initialize request argument(s) 

721 metric = logging_v2.LogMetric() 

722 metric.name = "name_value" 

723 metric.filter = "filter_value" 

724 

725 request = logging_v2.UpdateLogMetricRequest( 

726 metric_name="metric_name_value", 

727 metric=metric, 

728 ) 

729 

730 # Make the request 

731 response = await client.update_log_metric(request=request) 

732 

733 # Handle the response 

734 print(response) 

735 

736 Args: 

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

738 The request object. The parameters to UpdateLogMetric. 

739 metric_name (:class:`str`): 

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

741 

742 :: 

743 

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

745 

746 The updated metric must be provided in the request and 

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

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

749 new metric is created. 

750 

751 This corresponds to the ``metric_name`` field 

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

753 should not be set. 

754 metric (:class:`google.cloud.logging_v2.types.LogMetric`): 

755 Required. The updated metric. 

756 This corresponds to the ``metric`` field 

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

758 should not be set. 

759 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

760 should be retried. 

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

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

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

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

765 be of type `bytes`. 

766 

767 Returns: 

768 google.cloud.logging_v2.types.LogMetric: 

769 Describes a logs-based metric. The 

770 value of the metric is the number of log 

771 entries that match a logs filter in a 

772 given time interval. 

773 

774 Logs-based metrics can also be used to 

775 extract values from logs and create a 

776 distribution of the values. The 

777 distribution records the statistics of 

778 the extracted values along with an 

779 optional histogram of the values as 

780 specified by the bucket options. 

781 

782 """ 

783 # Create or coerce a protobuf request object. 

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

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

786 flattened_params = [metric_name, metric] 

787 has_flattened_params = ( 

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

789 ) 

790 if request is not None and has_flattened_params: 

791 raise ValueError( 

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

793 "the individual field arguments should be set." 

794 ) 

795 

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

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

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

799 request = logging_metrics.UpdateLogMetricRequest(request) 

800 

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

802 # request, apply these. 

803 if metric_name is not None: 

804 request.metric_name = metric_name 

805 if metric is not None: 

806 request.metric = metric 

807 

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

809 # and friendly error handling. 

810 rpc = self._client._transport._wrapped_methods[ 

811 self._client._transport.update_log_metric 

812 ] 

813 

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

815 # add these here. 

816 metadata = tuple(metadata) + ( 

817 gapic_v1.routing_header.to_grpc_metadata( 

818 (("metric_name", request.metric_name),) 

819 ), 

820 ) 

821 

822 # Validate the universe domain. 

823 self._client._validate_universe_domain() 

824 

825 # Send the request. 

826 response = await rpc( 

827 request, 

828 retry=retry, 

829 timeout=timeout, 

830 metadata=metadata, 

831 ) 

832 

833 # Done; return the response. 

834 return response 

835 

836 async def delete_log_metric( 

837 self, 

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

839 *, 

840 metric_name: Optional[str] = None, 

841 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

844 ) -> None: 

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

846 

847 .. code-block:: python 

848 

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

850 # code template only. 

851 # It will require modifications to work: 

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

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

854 # client as shown in: 

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

856 from google.cloud import logging_v2 

857 

858 async def sample_delete_log_metric(): 

859 # Create a client 

860 client = logging_v2.MetricsServiceV2AsyncClient() 

861 

862 # Initialize request argument(s) 

863 request = logging_v2.DeleteLogMetricRequest( 

864 metric_name="metric_name_value", 

865 ) 

866 

867 # Make the request 

868 await client.delete_log_metric(request=request) 

869 

870 Args: 

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

872 The request object. The parameters to DeleteLogMetric. 

873 metric_name (:class:`str`): 

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

875 

876 :: 

877 

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

879 

880 This corresponds to the ``metric_name`` field 

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

882 should not be set. 

883 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, 

884 should be retried. 

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

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

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

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

889 be of type `bytes`. 

890 """ 

891 # Create or coerce a protobuf request object. 

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

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

894 flattened_params = [metric_name] 

895 has_flattened_params = ( 

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

897 ) 

898 if request is not None and has_flattened_params: 

899 raise ValueError( 

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

901 "the individual field arguments should be set." 

902 ) 

903 

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

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

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

907 request = logging_metrics.DeleteLogMetricRequest(request) 

908 

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

910 # request, apply these. 

911 if metric_name is not None: 

912 request.metric_name = metric_name 

913 

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

915 # and friendly error handling. 

916 rpc = self._client._transport._wrapped_methods[ 

917 self._client._transport.delete_log_metric 

918 ] 

919 

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

921 # add these here. 

922 metadata = tuple(metadata) + ( 

923 gapic_v1.routing_header.to_grpc_metadata( 

924 (("metric_name", request.metric_name),) 

925 ), 

926 ) 

927 

928 # Validate the universe domain. 

929 self._client._validate_universe_domain() 

930 

931 # Send the request. 

932 await rpc( 

933 request, 

934 retry=retry, 

935 timeout=timeout, 

936 metadata=metadata, 

937 ) 

938 

939 async def list_operations( 

940 self, 

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

942 *, 

943 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

946 ) -> operations_pb2.ListOperationsResponse: 

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

948 

949 Args: 

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

951 The request object. Request message for 

952 `ListOperations` method. 

953 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, 

954 if any, should be retried. 

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

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

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

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

959 be of type `bytes`. 

960 Returns: 

961 ~.operations_pb2.ListOperationsResponse: 

962 Response message for ``ListOperations`` method. 

963 """ 

964 # Create or coerce a protobuf request object. 

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

966 # so it must be constructed via keyword expansion. 

967 if isinstance(request, dict): 

968 request = operations_pb2.ListOperationsRequest(**request) 

969 

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

971 # and friendly error handling. 

972 rpc = self.transport._wrapped_methods[self._client._transport.list_operations] 

973 

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

975 # add these here. 

976 metadata = tuple(metadata) + ( 

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

978 ) 

979 

980 # Validate the universe domain. 

981 self._client._validate_universe_domain() 

982 

983 # Send the request. 

984 response = await rpc( 

985 request, 

986 retry=retry, 

987 timeout=timeout, 

988 metadata=metadata, 

989 ) 

990 

991 # Done; return the response. 

992 return response 

993 

994 async def get_operation( 

995 self, 

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

997 *, 

998 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1001 ) -> operations_pb2.Operation: 

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

1003 

1004 Args: 

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

1006 The request object. Request message for 

1007 `GetOperation` method. 

1008 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, 

1009 if any, should be retried. 

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

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

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

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

1014 be of type `bytes`. 

1015 Returns: 

1016 ~.operations_pb2.Operation: 

1017 An ``Operation`` object. 

1018 """ 

1019 # Create or coerce a protobuf request object. 

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

1021 # so it must be constructed via keyword expansion. 

1022 if isinstance(request, dict): 

1023 request = operations_pb2.GetOperationRequest(**request) 

1024 

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

1026 # and friendly error handling. 

1027 rpc = self.transport._wrapped_methods[self._client._transport.get_operation] 

1028 

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

1030 # add these here. 

1031 metadata = tuple(metadata) + ( 

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

1033 ) 

1034 

1035 # Validate the universe domain. 

1036 self._client._validate_universe_domain() 

1037 

1038 # Send the request. 

1039 response = await rpc( 

1040 request, 

1041 retry=retry, 

1042 timeout=timeout, 

1043 metadata=metadata, 

1044 ) 

1045 

1046 # Done; return the response. 

1047 return response 

1048 

1049 async def cancel_operation( 

1050 self, 

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

1052 *, 

1053 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1056 ) -> None: 

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

1058 

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

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

1061 `google.rpc.Code.UNIMPLEMENTED`. 

1062 

1063 Args: 

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

1065 The request object. Request message for 

1066 `CancelOperation` method. 

1067 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, 

1068 if any, should be retried. 

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

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

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

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

1073 be of type `bytes`. 

1074 Returns: 

1075 None 

1076 """ 

1077 # Create or coerce a protobuf request object. 

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

1079 # so it must be constructed via keyword expansion. 

1080 if isinstance(request, dict): 

1081 request = operations_pb2.CancelOperationRequest(**request) 

1082 

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

1084 # and friendly error handling. 

1085 rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] 

1086 

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

1088 # add these here. 

1089 metadata = tuple(metadata) + ( 

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

1091 ) 

1092 

1093 # Validate the universe domain. 

1094 self._client._validate_universe_domain() 

1095 

1096 # Send the request. 

1097 await rpc( 

1098 request, 

1099 retry=retry, 

1100 timeout=timeout, 

1101 metadata=metadata, 

1102 ) 

1103 

1104 async def __aenter__(self) -> "MetricsServiceV2AsyncClient": 

1105 return self 

1106 

1107 async def __aexit__(self, exc_type, exc, tb): 

1108 await self.transport.close() 

1109 

1110 

1111DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1112 gapic_version=package_version.__version__ 

1113) 

1114 

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

1116 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1117 

1118 

1119__all__ = ("MetricsServiceV2AsyncClient",)