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

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

31 

32from google.cloud.logging_v2 import gapic_version as package_version 

33 

34from google.api_core.client_options import ClientOptions 

35from google.api_core import exceptions as core_exceptions 

36from google.api_core import gapic_v1 

37from google.api_core import retry_async as retries 

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

39from google.oauth2 import service_account # type: ignore 

40import google.protobuf 

41 

42 

43try: 

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

45except AttributeError: # pragma: NO COVER 

46 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore 

47 

48from google.api import distribution_pb2 # type: ignore 

49from google.api import metric_pb2 # type: ignore 

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

51from google.cloud.logging_v2.types import logging_metrics 

52from google.longrunning import operations_pb2 # type: ignore 

53from google.protobuf import timestamp_pb2 # type: ignore 

54from .transports.base import MetricsServiceV2Transport, DEFAULT_CLIENT_INFO 

55from .transports.grpc_asyncio import MetricsServiceV2GrpcAsyncIOTransport 

56from .client import MetricsServiceV2Client 

57 

58try: 

59 from google.api_core import client_logging # type: ignore 

60 

61 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

62except ImportError: # pragma: NO COVER 

63 CLIENT_LOGGING_SUPPORTED = False 

64 

65_LOGGER = std_logging.getLogger(__name__) 

66 

67 

68class MetricsServiceV2AsyncClient: 

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

70 

71 _client: MetricsServiceV2Client 

72 

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

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

75 DEFAULT_ENDPOINT = MetricsServiceV2Client.DEFAULT_ENDPOINT 

76 DEFAULT_MTLS_ENDPOINT = MetricsServiceV2Client.DEFAULT_MTLS_ENDPOINT 

77 _DEFAULT_ENDPOINT_TEMPLATE = MetricsServiceV2Client._DEFAULT_ENDPOINT_TEMPLATE 

78 _DEFAULT_UNIVERSE = MetricsServiceV2Client._DEFAULT_UNIVERSE 

79 

80 log_metric_path = staticmethod(MetricsServiceV2Client.log_metric_path) 

81 parse_log_metric_path = staticmethod(MetricsServiceV2Client.parse_log_metric_path) 

82 common_billing_account_path = staticmethod( 

83 MetricsServiceV2Client.common_billing_account_path 

84 ) 

85 parse_common_billing_account_path = staticmethod( 

86 MetricsServiceV2Client.parse_common_billing_account_path 

87 ) 

88 common_folder_path = staticmethod(MetricsServiceV2Client.common_folder_path) 

89 parse_common_folder_path = staticmethod( 

90 MetricsServiceV2Client.parse_common_folder_path 

91 ) 

92 common_organization_path = staticmethod( 

93 MetricsServiceV2Client.common_organization_path 

94 ) 

95 parse_common_organization_path = staticmethod( 

96 MetricsServiceV2Client.parse_common_organization_path 

97 ) 

98 common_project_path = staticmethod(MetricsServiceV2Client.common_project_path) 

99 parse_common_project_path = staticmethod( 

100 MetricsServiceV2Client.parse_common_project_path 

101 ) 

102 common_location_path = staticmethod(MetricsServiceV2Client.common_location_path) 

103 parse_common_location_path = staticmethod( 

104 MetricsServiceV2Client.parse_common_location_path 

105 ) 

106 

107 @classmethod 

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

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

110 info. 

111 

112 Args: 

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

114 args: Additional arguments to pass to the constructor. 

115 kwargs: Additional arguments to pass to the constructor. 

116 

117 Returns: 

118 MetricsServiceV2AsyncClient: The constructed client. 

119 """ 

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

121 

122 @classmethod 

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

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

125 file. 

126 

127 Args: 

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

129 file. 

130 args: Additional arguments to pass to the constructor. 

131 kwargs: Additional arguments to pass to the constructor. 

132 

133 Returns: 

134 MetricsServiceV2AsyncClient: The constructed client. 

135 """ 

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

137 

138 from_service_account_json = from_service_account_file 

139 

140 @classmethod 

141 def get_mtls_endpoint_and_cert_source( 

142 cls, client_options: Optional[ClientOptions] = None 

143 ): 

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

145 

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

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

148 client cert source is None. 

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

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

151 source is None. 

152 

153 The API endpoint is determined in the following order: 

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

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

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

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

158 use the default API endpoint. 

159 

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

161 

162 Args: 

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

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

165 in this method. 

166 

167 Returns: 

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

169 client cert source to use. 

170 

171 Raises: 

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

173 """ 

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

175 

176 @property 

177 def transport(self) -> MetricsServiceV2Transport: 

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

179 

180 Returns: 

181 MetricsServiceV2Transport: The transport used by the client instance. 

182 """ 

183 return self._client.transport 

184 

185 @property 

186 def api_endpoint(self): 

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

188 

189 Returns: 

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

191 """ 

192 return self._client._api_endpoint 

193 

194 @property 

195 def universe_domain(self) -> str: 

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

197 

198 Returns: 

199 str: The universe domain used 

200 by the client instance. 

201 """ 

202 return self._client._universe_domain 

203 

204 get_transport_class = MetricsServiceV2Client.get_transport_class 

205 

206 def __init__( 

207 self, 

208 *, 

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

210 transport: Optional[ 

211 Union[ 

212 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] 

213 ] 

214 ] = "grpc_asyncio", 

215 client_options: Optional[ClientOptions] = None, 

216 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

217 ) -> None: 

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

219 

220 Args: 

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

222 authorization credentials to attach to requests. These 

223 credentials identify the application to the service; if none 

224 are specified, the client will attempt to ascertain the 

225 credentials from the environment. 

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

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

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

229 arguments as used in the MetricsServiceV2Transport constructor. 

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

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

232 Custom options for the client. 

233 

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

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

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

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

238 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

239 variable, which have one of the following values: 

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

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

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

243 the default value). 

244 

245 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

247 to provide a client certificate for mTLS transport. If 

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

249 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

250 set, no client certificate will be used. 

251 

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

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

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

255 currently not supported for mTLS. 

256 

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

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

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

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

261 your own client library. 

262 

263 Raises: 

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

265 creation failed for any reason. 

266 """ 

267 self._client = MetricsServiceV2Client( 

268 credentials=credentials, 

269 transport=transport, 

270 client_options=client_options, 

271 client_info=client_info, 

272 ) 

273 

274 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

275 std_logging.DEBUG 

276 ): # pragma: NO COVER 

277 _LOGGER.debug( 

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

279 extra={ 

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

281 "universeDomain": getattr( 

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

283 ), 

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

285 "credentialsInfo": getattr( 

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

287 )(), 

288 } 

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

290 else { 

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

292 "credentialsType": None, 

293 }, 

294 ) 

295 

296 async def list_log_metrics( 

297 self, 

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

299 *, 

300 parent: Optional[str] = None, 

301 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

304 ) -> pagers.ListLogMetricsAsyncPager: 

305 r"""Lists logs-based metrics. 

306 

307 .. code-block:: python 

308 

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

310 # code template only. 

311 # It will require modifications to work: 

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

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

314 # client as shown in: 

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

316 from google.cloud import logging_v2 

317 

318 async def sample_list_log_metrics(): 

319 # Create a client 

320 client = logging_v2.MetricsServiceV2AsyncClient() 

321 

322 # Initialize request argument(s) 

323 request = logging_v2.ListLogMetricsRequest( 

324 parent="parent_value", 

325 ) 

326 

327 # Make the request 

328 page_result = client.list_log_metrics(request=request) 

329 

330 # Handle the response 

331 async for response in page_result: 

332 print(response) 

333 

334 Args: 

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

336 The request object. The parameters to ListLogMetrics. 

337 parent (:class:`str`): 

338 Required. The name of the project containing the 

339 metrics: 

340 

341 :: 

342 

343 "projects/[PROJECT_ID]" 

344 

345 This corresponds to the ``parent`` field 

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

347 should not be set. 

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

349 should be retried. 

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

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

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

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

354 be of type `bytes`. 

355 

356 Returns: 

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

358 Result returned from ListLogMetrics. 

359 

360 Iterating over this object will yield 

361 results and resolve additional pages 

362 automatically. 

363 

364 """ 

365 # Create or coerce a protobuf request object. 

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

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

368 flattened_params = [parent] 

369 has_flattened_params = ( 

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

371 ) 

372 if request is not None and has_flattened_params: 

373 raise ValueError( 

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

375 "the individual field arguments should be set." 

376 ) 

377 

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

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

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

381 request = logging_metrics.ListLogMetricsRequest(request) 

382 

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

384 # request, apply these. 

385 if parent is not None: 

386 request.parent = parent 

387 

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

389 # and friendly error handling. 

390 rpc = self._client._transport._wrapped_methods[ 

391 self._client._transport.list_log_metrics 

392 ] 

393 

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

395 # add these here. 

396 metadata = tuple(metadata) + ( 

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

398 ) 

399 

400 # Validate the universe domain. 

401 self._client._validate_universe_domain() 

402 

403 # Send the request. 

404 response = await rpc( 

405 request, 

406 retry=retry, 

407 timeout=timeout, 

408 metadata=metadata, 

409 ) 

410 

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

412 # an `__aiter__` convenience method. 

413 response = pagers.ListLogMetricsAsyncPager( 

414 method=rpc, 

415 request=request, 

416 response=response, 

417 retry=retry, 

418 timeout=timeout, 

419 metadata=metadata, 

420 ) 

421 

422 # Done; return the response. 

423 return response 

424 

425 async def get_log_metric( 

426 self, 

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

428 *, 

429 metric_name: Optional[str] = None, 

430 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

433 ) -> logging_metrics.LogMetric: 

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

435 

436 .. code-block:: python 

437 

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

439 # code template only. 

440 # It will require modifications to work: 

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

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

443 # client as shown in: 

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

445 from google.cloud import logging_v2 

446 

447 async def sample_get_log_metric(): 

448 # Create a client 

449 client = logging_v2.MetricsServiceV2AsyncClient() 

450 

451 # Initialize request argument(s) 

452 request = logging_v2.GetLogMetricRequest( 

453 metric_name="metric_name_value", 

454 ) 

455 

456 # Make the request 

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

458 

459 # Handle the response 

460 print(response) 

461 

462 Args: 

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

464 The request object. The parameters to GetLogMetric. 

465 metric_name (:class:`str`): 

466 Required. The resource name of the desired metric: 

467 

468 :: 

469 

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

471 

472 This corresponds to the ``metric_name`` field 

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

474 should not be set. 

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

476 should be retried. 

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

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

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

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

481 be of type `bytes`. 

482 

483 Returns: 

484 google.cloud.logging_v2.types.LogMetric: 

485 Describes a logs-based metric. The 

486 value of the metric is the number of log 

487 entries that match a logs filter in a 

488 given time interval. 

489 

490 Logs-based metrics can also be used to 

491 extract values from logs and create a 

492 distribution of the values. The 

493 distribution records the statistics of 

494 the extracted values along with an 

495 optional histogram of the values as 

496 specified by the bucket options. 

497 

498 """ 

499 # Create or coerce a protobuf request object. 

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

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

502 flattened_params = [metric_name] 

503 has_flattened_params = ( 

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

505 ) 

506 if request is not None and has_flattened_params: 

507 raise ValueError( 

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

509 "the individual field arguments should be set." 

510 ) 

511 

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

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

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

515 request = logging_metrics.GetLogMetricRequest(request) 

516 

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

518 # request, apply these. 

519 if metric_name is not None: 

520 request.metric_name = metric_name 

521 

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

523 # and friendly error handling. 

524 rpc = self._client._transport._wrapped_methods[ 

525 self._client._transport.get_log_metric 

526 ] 

527 

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

529 # add these here. 

530 metadata = tuple(metadata) + ( 

531 gapic_v1.routing_header.to_grpc_metadata( 

532 (("metric_name", request.metric_name),) 

533 ), 

534 ) 

535 

536 # Validate the universe domain. 

537 self._client._validate_universe_domain() 

538 

539 # Send the request. 

540 response = await rpc( 

541 request, 

542 retry=retry, 

543 timeout=timeout, 

544 metadata=metadata, 

545 ) 

546 

547 # Done; return the response. 

548 return response 

549 

550 async def create_log_metric( 

551 self, 

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

553 *, 

554 parent: Optional[str] = None, 

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

556 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

559 ) -> logging_metrics.LogMetric: 

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

561 

562 .. code-block:: python 

563 

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

565 # code template only. 

566 # It will require modifications to work: 

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

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

569 # client as shown in: 

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

571 from google.cloud import logging_v2 

572 

573 async def sample_create_log_metric(): 

574 # Create a client 

575 client = logging_v2.MetricsServiceV2AsyncClient() 

576 

577 # Initialize request argument(s) 

578 metric = logging_v2.LogMetric() 

579 metric.name = "name_value" 

580 metric.filter = "filter_value" 

581 

582 request = logging_v2.CreateLogMetricRequest( 

583 parent="parent_value", 

584 metric=metric, 

585 ) 

586 

587 # Make the request 

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

589 

590 # Handle the response 

591 print(response) 

592 

593 Args: 

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

595 The request object. The parameters to CreateLogMetric. 

596 parent (:class:`str`): 

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

598 create the metric: 

599 

600 :: 

601 

602 "projects/[PROJECT_ID]" 

603 

604 The new metric must be provided in the request. 

605 

606 This corresponds to the ``parent`` field 

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

608 should not be set. 

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

610 Required. The new logs-based metric, 

611 which must not have an identifier that 

612 already exists. 

613 

614 This corresponds to the ``metric`` field 

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

616 should not be set. 

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

618 should be retried. 

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

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

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

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

623 be of type `bytes`. 

624 

625 Returns: 

626 google.cloud.logging_v2.types.LogMetric: 

627 Describes a logs-based metric. The 

628 value of the metric is the number of log 

629 entries that match a logs filter in a 

630 given time interval. 

631 

632 Logs-based metrics can also be used to 

633 extract values from logs and create a 

634 distribution of the values. The 

635 distribution records the statistics of 

636 the extracted values along with an 

637 optional histogram of the values as 

638 specified by the bucket options. 

639 

640 """ 

641 # Create or coerce a protobuf request object. 

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

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

644 flattened_params = [parent, metric] 

645 has_flattened_params = ( 

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

647 ) 

648 if request is not None and has_flattened_params: 

649 raise ValueError( 

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

651 "the individual field arguments should be set." 

652 ) 

653 

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

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

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

657 request = logging_metrics.CreateLogMetricRequest(request) 

658 

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

660 # request, apply these. 

661 if parent is not None: 

662 request.parent = parent 

663 if metric is not None: 

664 request.metric = metric 

665 

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

667 # and friendly error handling. 

668 rpc = self._client._transport._wrapped_methods[ 

669 self._client._transport.create_log_metric 

670 ] 

671 

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

673 # add these here. 

674 metadata = tuple(metadata) + ( 

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

676 ) 

677 

678 # Validate the universe domain. 

679 self._client._validate_universe_domain() 

680 

681 # Send the request. 

682 response = await rpc( 

683 request, 

684 retry=retry, 

685 timeout=timeout, 

686 metadata=metadata, 

687 ) 

688 

689 # Done; return the response. 

690 return response 

691 

692 async def update_log_metric( 

693 self, 

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

695 *, 

696 metric_name: Optional[str] = None, 

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

698 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

701 ) -> logging_metrics.LogMetric: 

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

703 

704 .. code-block:: python 

705 

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

707 # code template only. 

708 # It will require modifications to work: 

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

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

711 # client as shown in: 

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

713 from google.cloud import logging_v2 

714 

715 async def sample_update_log_metric(): 

716 # Create a client 

717 client = logging_v2.MetricsServiceV2AsyncClient() 

718 

719 # Initialize request argument(s) 

720 metric = logging_v2.LogMetric() 

721 metric.name = "name_value" 

722 metric.filter = "filter_value" 

723 

724 request = logging_v2.UpdateLogMetricRequest( 

725 metric_name="metric_name_value", 

726 metric=metric, 

727 ) 

728 

729 # Make the request 

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

731 

732 # Handle the response 

733 print(response) 

734 

735 Args: 

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

737 The request object. The parameters to UpdateLogMetric. 

738 metric_name (:class:`str`): 

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

740 

741 :: 

742 

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

744 

745 The updated metric must be provided in the request and 

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

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

748 new metric is created. 

749 

750 This corresponds to the ``metric_name`` field 

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

752 should not be set. 

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

754 Required. The updated metric. 

755 This corresponds to the ``metric`` field 

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

757 should not be set. 

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

759 should be retried. 

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

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

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

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

764 be of type `bytes`. 

765 

766 Returns: 

767 google.cloud.logging_v2.types.LogMetric: 

768 Describes a logs-based metric. The 

769 value of the metric is the number of log 

770 entries that match a logs filter in a 

771 given time interval. 

772 

773 Logs-based metrics can also be used to 

774 extract values from logs and create a 

775 distribution of the values. The 

776 distribution records the statistics of 

777 the extracted values along with an 

778 optional histogram of the values as 

779 specified by the bucket options. 

780 

781 """ 

782 # Create or coerce a protobuf request object. 

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

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

785 flattened_params = [metric_name, metric] 

786 has_flattened_params = ( 

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

788 ) 

789 if request is not None and has_flattened_params: 

790 raise ValueError( 

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

792 "the individual field arguments should be set." 

793 ) 

794 

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

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

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

798 request = logging_metrics.UpdateLogMetricRequest(request) 

799 

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

801 # request, apply these. 

802 if metric_name is not None: 

803 request.metric_name = metric_name 

804 if metric is not None: 

805 request.metric = metric 

806 

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

808 # and friendly error handling. 

809 rpc = self._client._transport._wrapped_methods[ 

810 self._client._transport.update_log_metric 

811 ] 

812 

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

814 # add these here. 

815 metadata = tuple(metadata) + ( 

816 gapic_v1.routing_header.to_grpc_metadata( 

817 (("metric_name", request.metric_name),) 

818 ), 

819 ) 

820 

821 # Validate the universe domain. 

822 self._client._validate_universe_domain() 

823 

824 # Send the request. 

825 response = await rpc( 

826 request, 

827 retry=retry, 

828 timeout=timeout, 

829 metadata=metadata, 

830 ) 

831 

832 # Done; return the response. 

833 return response 

834 

835 async def delete_log_metric( 

836 self, 

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

838 *, 

839 metric_name: Optional[str] = None, 

840 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

843 ) -> None: 

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

845 

846 .. code-block:: python 

847 

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

849 # code template only. 

850 # It will require modifications to work: 

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

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

853 # client as shown in: 

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

855 from google.cloud import logging_v2 

856 

857 async def sample_delete_log_metric(): 

858 # Create a client 

859 client = logging_v2.MetricsServiceV2AsyncClient() 

860 

861 # Initialize request argument(s) 

862 request = logging_v2.DeleteLogMetricRequest( 

863 metric_name="metric_name_value", 

864 ) 

865 

866 # Make the request 

867 await client.delete_log_metric(request=request) 

868 

869 Args: 

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

871 The request object. The parameters to DeleteLogMetric. 

872 metric_name (:class:`str`): 

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

874 

875 :: 

876 

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

878 

879 This corresponds to the ``metric_name`` field 

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

881 should not be set. 

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

883 should be retried. 

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

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

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

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

888 be of type `bytes`. 

889 """ 

890 # Create or coerce a protobuf request object. 

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

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

893 flattened_params = [metric_name] 

894 has_flattened_params = ( 

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

896 ) 

897 if request is not None and has_flattened_params: 

898 raise ValueError( 

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

900 "the individual field arguments should be set." 

901 ) 

902 

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

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

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

906 request = logging_metrics.DeleteLogMetricRequest(request) 

907 

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

909 # request, apply these. 

910 if metric_name is not None: 

911 request.metric_name = metric_name 

912 

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

914 # and friendly error handling. 

915 rpc = self._client._transport._wrapped_methods[ 

916 self._client._transport.delete_log_metric 

917 ] 

918 

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

920 # add these here. 

921 metadata = tuple(metadata) + ( 

922 gapic_v1.routing_header.to_grpc_metadata( 

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

924 ), 

925 ) 

926 

927 # Validate the universe domain. 

928 self._client._validate_universe_domain() 

929 

930 # Send the request. 

931 await rpc( 

932 request, 

933 retry=retry, 

934 timeout=timeout, 

935 metadata=metadata, 

936 ) 

937 

938 async def list_operations( 

939 self, 

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

941 *, 

942 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

945 ) -> operations_pb2.ListOperationsResponse: 

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

947 

948 Args: 

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

950 The request object. Request message for 

951 `ListOperations` method. 

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

953 if any, should be retried. 

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

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

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

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

958 be of type `bytes`. 

959 Returns: 

960 ~.operations_pb2.ListOperationsResponse: 

961 Response message for ``ListOperations`` method. 

962 """ 

963 # Create or coerce a protobuf request object. 

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

965 # so it must be constructed via keyword expansion. 

966 if isinstance(request, dict): 

967 request = operations_pb2.ListOperationsRequest(**request) 

968 

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

970 # and friendly error handling. 

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

972 

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

974 # add these here. 

975 metadata = tuple(metadata) + ( 

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

977 ) 

978 

979 # Validate the universe domain. 

980 self._client._validate_universe_domain() 

981 

982 # Send the request. 

983 response = await rpc( 

984 request, 

985 retry=retry, 

986 timeout=timeout, 

987 metadata=metadata, 

988 ) 

989 

990 # Done; return the response. 

991 return response 

992 

993 async def get_operation( 

994 self, 

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

996 *, 

997 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1000 ) -> operations_pb2.Operation: 

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

1002 

1003 Args: 

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

1005 The request object. Request message for 

1006 `GetOperation` method. 

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

1008 if any, should be retried. 

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

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

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

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

1013 be of type `bytes`. 

1014 Returns: 

1015 ~.operations_pb2.Operation: 

1016 An ``Operation`` object. 

1017 """ 

1018 # Create or coerce a protobuf request object. 

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

1020 # so it must be constructed via keyword expansion. 

1021 if isinstance(request, dict): 

1022 request = operations_pb2.GetOperationRequest(**request) 

1023 

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

1025 # and friendly error handling. 

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

1027 

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

1029 # add these here. 

1030 metadata = tuple(metadata) + ( 

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

1032 ) 

1033 

1034 # Validate the universe domain. 

1035 self._client._validate_universe_domain() 

1036 

1037 # Send the request. 

1038 response = await rpc( 

1039 request, 

1040 retry=retry, 

1041 timeout=timeout, 

1042 metadata=metadata, 

1043 ) 

1044 

1045 # Done; return the response. 

1046 return response 

1047 

1048 async def cancel_operation( 

1049 self, 

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

1051 *, 

1052 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1055 ) -> None: 

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

1057 

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

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

1060 `google.rpc.Code.UNIMPLEMENTED`. 

1061 

1062 Args: 

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

1064 The request object. Request message for 

1065 `CancelOperation` method. 

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

1067 if any, should be retried. 

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

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

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

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

1072 be of type `bytes`. 

1073 Returns: 

1074 None 

1075 """ 

1076 # Create or coerce a protobuf request object. 

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

1078 # so it must be constructed via keyword expansion. 

1079 if isinstance(request, dict): 

1080 request = operations_pb2.CancelOperationRequest(**request) 

1081 

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

1083 # and friendly error handling. 

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

1085 

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

1087 # add these here. 

1088 metadata = tuple(metadata) + ( 

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

1090 ) 

1091 

1092 # Validate the universe domain. 

1093 self._client._validate_universe_domain() 

1094 

1095 # Send the request. 

1096 await rpc( 

1097 request, 

1098 retry=retry, 

1099 timeout=timeout, 

1100 metadata=metadata, 

1101 ) 

1102 

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

1104 return self 

1105 

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

1107 await self.transport.close() 

1108 

1109 

1110DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1111 gapic_version=package_version.__version__ 

1112) 

1113 

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

1115 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1116 

1117 

1118__all__ = ("MetricsServiceV2AsyncClient",)