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

173 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.cloud.logging_v2.services.metrics_service_v2 import pagers 

50from google.cloud.logging_v2.types import logging_metrics 

51from google.longrunning import operations_pb2 # type: ignore 

52import google.api.distribution_pb2 as distribution_pb2 # type: ignore 

53import google.api.metric_pb2 as metric_pb2 # type: ignore 

54import google.protobuf.timestamp_pb2 as 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 sa_info_func = ( 

122 MetricsServiceV2Client.from_service_account_info.__func__ # type: ignore 

123 ) 

124 return sa_info_func(MetricsServiceV2AsyncClient, info, *args, **kwargs) 

125 

126 @classmethod 

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

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

129 file. 

130 

131 Args: 

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

133 file. 

134 args: Additional arguments to pass to the constructor. 

135 kwargs: Additional arguments to pass to the constructor. 

136 

137 Returns: 

138 MetricsServiceV2AsyncClient: The constructed client. 

139 """ 

140 sa_file_func = ( 

141 MetricsServiceV2Client.from_service_account_file.__func__ # type: ignore 

142 ) 

143 return sa_file_func(MetricsServiceV2AsyncClient, filename, *args, **kwargs) 

144 

145 from_service_account_json = from_service_account_file 

146 

147 @classmethod 

148 def get_mtls_endpoint_and_cert_source( 

149 cls, client_options: Optional[ClientOptions] = None 

150 ): 

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

152 

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

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

155 client cert source is None. 

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

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

158 source is None. 

159 

160 The API endpoint is determined in the following order: 

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

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

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

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

165 use the default API endpoint. 

166 

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

168 

169 Args: 

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

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

172 in this method. 

173 

174 Returns: 

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

176 client cert source to use. 

177 

178 Raises: 

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

180 """ 

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

182 

183 @property 

184 def transport(self) -> MetricsServiceV2Transport: 

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

186 

187 Returns: 

188 MetricsServiceV2Transport: The transport used by the client instance. 

189 """ 

190 return self._client.transport 

191 

192 @property 

193 def api_endpoint(self): 

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

195 

196 Returns: 

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

198 """ 

199 return self._client._api_endpoint 

200 

201 @property 

202 def universe_domain(self) -> str: 

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

204 

205 Returns: 

206 str: The universe domain used 

207 by the client instance. 

208 """ 

209 return self._client._universe_domain 

210 

211 get_transport_class = MetricsServiceV2Client.get_transport_class 

212 

213 def __init__( 

214 self, 

215 *, 

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

217 transport: Optional[ 

218 Union[ 

219 str, MetricsServiceV2Transport, Callable[..., MetricsServiceV2Transport] 

220 ] 

221 ] = "grpc_asyncio", 

222 client_options: Optional[ClientOptions] = None, 

223 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

224 ) -> None: 

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

226 

227 Args: 

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

229 authorization credentials to attach to requests. These 

230 credentials identify the application to the service; if none 

231 are specified, the client will attempt to ascertain the 

232 credentials from the environment. 

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

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

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

236 arguments as used in the MetricsServiceV2Transport constructor. 

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

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

239 Custom options for the client. 

240 

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

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

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

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

245 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

246 variable, which have one of the following values: 

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

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

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

250 the default value). 

251 

252 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

254 to provide a client certificate for mTLS transport. If 

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

256 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

257 set, no client certificate will be used. 

258 

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

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

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

262 currently not supported for mTLS. 

263 

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

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

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

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

268 your own client library. 

269 

270 Raises: 

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

272 creation failed for any reason. 

273 """ 

274 self._client = MetricsServiceV2Client( 

275 credentials=credentials, 

276 transport=transport, 

277 client_options=client_options, 

278 client_info=client_info, 

279 ) 

280 

281 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

282 std_logging.DEBUG 

283 ): # pragma: NO COVER 

284 _LOGGER.debug( 

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

286 extra={ 

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

288 "universeDomain": getattr( 

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

290 ), 

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

292 "credentialsInfo": getattr( 

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

294 )(), 

295 } 

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

297 else { 

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

299 "credentialsType": None, 

300 }, 

301 ) 

302 

303 async def list_log_metrics( 

304 self, 

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

306 *, 

307 parent: Optional[str] = None, 

308 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

311 ) -> pagers.ListLogMetricsAsyncPager: 

312 r"""Lists logs-based metrics. 

313 

314 .. code-block:: python 

315 

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

317 # code template only. 

318 # It will require modifications to work: 

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

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

321 # client as shown in: 

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

323 from google.cloud import logging_v2 

324 

325 async def sample_list_log_metrics(): 

326 # Create a client 

327 client = logging_v2.MetricsServiceV2AsyncClient() 

328 

329 # Initialize request argument(s) 

330 request = logging_v2.ListLogMetricsRequest( 

331 parent="parent_value", 

332 ) 

333 

334 # Make the request 

335 page_result = client.list_log_metrics(request=request) 

336 

337 # Handle the response 

338 async for response in page_result: 

339 print(response) 

340 

341 Args: 

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

343 The request object. The parameters to ListLogMetrics. 

344 parent (:class:`str`): 

345 Required. The name of the project containing the 

346 metrics: 

347 

348 :: 

349 

350 "projects/[PROJECT_ID]" 

351 

352 This corresponds to the ``parent`` field 

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

354 should not be set. 

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

356 should be retried. 

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

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

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

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

361 be of type `bytes`. 

362 

363 Returns: 

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

365 Result returned from ListLogMetrics. 

366 

367 Iterating over this object will yield 

368 results and resolve additional pages 

369 automatically. 

370 

371 """ 

372 # Create or coerce a protobuf request object. 

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

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

375 flattened_params = [parent] 

376 has_flattened_params = ( 

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

378 ) 

379 if request is not None and has_flattened_params: 

380 raise ValueError( 

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

382 "the individual field arguments should be set." 

383 ) 

384 

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

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

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

388 request = logging_metrics.ListLogMetricsRequest(request) 

389 

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

391 # request, apply these. 

392 if parent is not None: 

393 request.parent = parent 

394 

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

396 # and friendly error handling. 

397 rpc = self._client._transport._wrapped_methods[ 

398 self._client._transport.list_log_metrics 

399 ] 

400 

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

402 # add these here. 

403 metadata = tuple(metadata) + ( 

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

405 ) 

406 

407 # Validate the universe domain. 

408 self._client._validate_universe_domain() 

409 

410 # Send the request. 

411 response = await rpc( 

412 request, 

413 retry=retry, 

414 timeout=timeout, 

415 metadata=metadata, 

416 ) 

417 

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

419 # an `__aiter__` convenience method. 

420 response = pagers.ListLogMetricsAsyncPager( 

421 method=rpc, 

422 request=request, 

423 response=response, 

424 retry=retry, 

425 timeout=timeout, 

426 metadata=metadata, 

427 ) 

428 

429 # Done; return the response. 

430 return response 

431 

432 async def get_log_metric( 

433 self, 

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

435 *, 

436 metric_name: Optional[str] = None, 

437 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

440 ) -> logging_metrics.LogMetric: 

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

442 

443 .. code-block:: python 

444 

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

446 # code template only. 

447 # It will require modifications to work: 

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

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

450 # client as shown in: 

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

452 from google.cloud import logging_v2 

453 

454 async def sample_get_log_metric(): 

455 # Create a client 

456 client = logging_v2.MetricsServiceV2AsyncClient() 

457 

458 # Initialize request argument(s) 

459 request = logging_v2.GetLogMetricRequest( 

460 metric_name="metric_name_value", 

461 ) 

462 

463 # Make the request 

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

465 

466 # Handle the response 

467 print(response) 

468 

469 Args: 

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

471 The request object. The parameters to GetLogMetric. 

472 metric_name (:class:`str`): 

473 Required. The resource name of the desired metric: 

474 

475 :: 

476 

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

478 

479 This corresponds to the ``metric_name`` field 

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

481 should not be set. 

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

483 should be retried. 

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

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

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

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

488 be of type `bytes`. 

489 

490 Returns: 

491 google.cloud.logging_v2.types.LogMetric: 

492 Describes a logs-based metric. The 

493 value of the metric is the number of log 

494 entries that match a logs filter in a 

495 given time interval. 

496 

497 Logs-based metrics can also be used to 

498 extract values from logs and create a 

499 distribution of the values. The 

500 distribution records the statistics of 

501 the extracted values along with an 

502 optional histogram of the values as 

503 specified by the bucket options. 

504 

505 """ 

506 # Create or coerce a protobuf request object. 

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

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

509 flattened_params = [metric_name] 

510 has_flattened_params = ( 

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

512 ) 

513 if request is not None and has_flattened_params: 

514 raise ValueError( 

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

516 "the individual field arguments should be set." 

517 ) 

518 

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

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

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

522 request = logging_metrics.GetLogMetricRequest(request) 

523 

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

525 # request, apply these. 

526 if metric_name is not None: 

527 request.metric_name = metric_name 

528 

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

530 # and friendly error handling. 

531 rpc = self._client._transport._wrapped_methods[ 

532 self._client._transport.get_log_metric 

533 ] 

534 

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

536 # add these here. 

537 metadata = tuple(metadata) + ( 

538 gapic_v1.routing_header.to_grpc_metadata( 

539 (("metric_name", request.metric_name),) 

540 ), 

541 ) 

542 

543 # Validate the universe domain. 

544 self._client._validate_universe_domain() 

545 

546 # Send the request. 

547 response = await rpc( 

548 request, 

549 retry=retry, 

550 timeout=timeout, 

551 metadata=metadata, 

552 ) 

553 

554 # Done; return the response. 

555 return response 

556 

557 async def create_log_metric( 

558 self, 

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

560 *, 

561 parent: Optional[str] = None, 

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

563 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

566 ) -> logging_metrics.LogMetric: 

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

568 

569 .. code-block:: python 

570 

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

572 # code template only. 

573 # It will require modifications to work: 

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

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

576 # client as shown in: 

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

578 from google.cloud import logging_v2 

579 

580 async def sample_create_log_metric(): 

581 # Create a client 

582 client = logging_v2.MetricsServiceV2AsyncClient() 

583 

584 # Initialize request argument(s) 

585 metric = logging_v2.LogMetric() 

586 metric.name = "name_value" 

587 metric.filter = "filter_value" 

588 

589 request = logging_v2.CreateLogMetricRequest( 

590 parent="parent_value", 

591 metric=metric, 

592 ) 

593 

594 # Make the request 

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

596 

597 # Handle the response 

598 print(response) 

599 

600 Args: 

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

602 The request object. The parameters to CreateLogMetric. 

603 parent (:class:`str`): 

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

605 create the metric: 

606 

607 :: 

608 

609 "projects/[PROJECT_ID]" 

610 

611 The new metric must be provided in the request. 

612 

613 This corresponds to the ``parent`` field 

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

615 should not be set. 

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

617 Required. The new logs-based metric, 

618 which must not have an identifier that 

619 already exists. 

620 

621 This corresponds to the ``metric`` field 

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

623 should not be set. 

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

625 should be retried. 

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

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

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

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

630 be of type `bytes`. 

631 

632 Returns: 

633 google.cloud.logging_v2.types.LogMetric: 

634 Describes a logs-based metric. The 

635 value of the metric is the number of log 

636 entries that match a logs filter in a 

637 given time interval. 

638 

639 Logs-based metrics can also be used to 

640 extract values from logs and create a 

641 distribution of the values. The 

642 distribution records the statistics of 

643 the extracted values along with an 

644 optional histogram of the values as 

645 specified by the bucket options. 

646 

647 """ 

648 # Create or coerce a protobuf request object. 

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

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

651 flattened_params = [parent, metric] 

652 has_flattened_params = ( 

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

654 ) 

655 if request is not None and has_flattened_params: 

656 raise ValueError( 

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

658 "the individual field arguments should be set." 

659 ) 

660 

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

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

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

664 request = logging_metrics.CreateLogMetricRequest(request) 

665 

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

667 # request, apply these. 

668 if parent is not None: 

669 request.parent = parent 

670 if metric is not None: 

671 request.metric = metric 

672 

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

674 # and friendly error handling. 

675 rpc = self._client._transport._wrapped_methods[ 

676 self._client._transport.create_log_metric 

677 ] 

678 

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

680 # add these here. 

681 metadata = tuple(metadata) + ( 

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

683 ) 

684 

685 # Validate the universe domain. 

686 self._client._validate_universe_domain() 

687 

688 # Send the request. 

689 response = await rpc( 

690 request, 

691 retry=retry, 

692 timeout=timeout, 

693 metadata=metadata, 

694 ) 

695 

696 # Done; return the response. 

697 return response 

698 

699 async def update_log_metric( 

700 self, 

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

702 *, 

703 metric_name: Optional[str] = None, 

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

705 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

708 ) -> logging_metrics.LogMetric: 

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

710 

711 .. code-block:: python 

712 

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

714 # code template only. 

715 # It will require modifications to work: 

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

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

718 # client as shown in: 

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

720 from google.cloud import logging_v2 

721 

722 async def sample_update_log_metric(): 

723 # Create a client 

724 client = logging_v2.MetricsServiceV2AsyncClient() 

725 

726 # Initialize request argument(s) 

727 metric = logging_v2.LogMetric() 

728 metric.name = "name_value" 

729 metric.filter = "filter_value" 

730 

731 request = logging_v2.UpdateLogMetricRequest( 

732 metric_name="metric_name_value", 

733 metric=metric, 

734 ) 

735 

736 # Make the request 

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

738 

739 # Handle the response 

740 print(response) 

741 

742 Args: 

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

744 The request object. The parameters to UpdateLogMetric. 

745 metric_name (:class:`str`): 

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

747 

748 :: 

749 

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

751 

752 The updated metric must be provided in the request and 

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

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

755 new metric is created. 

756 

757 This corresponds to the ``metric_name`` field 

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

759 should not be set. 

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

761 Required. The updated metric. 

762 This corresponds to the ``metric`` field 

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

764 should not be set. 

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

766 should be retried. 

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

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

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

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

771 be of type `bytes`. 

772 

773 Returns: 

774 google.cloud.logging_v2.types.LogMetric: 

775 Describes a logs-based metric. The 

776 value of the metric is the number of log 

777 entries that match a logs filter in a 

778 given time interval. 

779 

780 Logs-based metrics can also be used to 

781 extract values from logs and create a 

782 distribution of the values. The 

783 distribution records the statistics of 

784 the extracted values along with an 

785 optional histogram of the values as 

786 specified by the bucket options. 

787 

788 """ 

789 # Create or coerce a protobuf request object. 

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

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

792 flattened_params = [metric_name, metric] 

793 has_flattened_params = ( 

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

795 ) 

796 if request is not None and has_flattened_params: 

797 raise ValueError( 

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

799 "the individual field arguments should be set." 

800 ) 

801 

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

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

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

805 request = logging_metrics.UpdateLogMetricRequest(request) 

806 

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

808 # request, apply these. 

809 if metric_name is not None: 

810 request.metric_name = metric_name 

811 if metric is not None: 

812 request.metric = metric 

813 

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

815 # and friendly error handling. 

816 rpc = self._client._transport._wrapped_methods[ 

817 self._client._transport.update_log_metric 

818 ] 

819 

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

821 # add these here. 

822 metadata = tuple(metadata) + ( 

823 gapic_v1.routing_header.to_grpc_metadata( 

824 (("metric_name", request.metric_name),) 

825 ), 

826 ) 

827 

828 # Validate the universe domain. 

829 self._client._validate_universe_domain() 

830 

831 # Send the request. 

832 response = await rpc( 

833 request, 

834 retry=retry, 

835 timeout=timeout, 

836 metadata=metadata, 

837 ) 

838 

839 # Done; return the response. 

840 return response 

841 

842 async def delete_log_metric( 

843 self, 

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

845 *, 

846 metric_name: Optional[str] = None, 

847 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

850 ) -> None: 

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

852 

853 .. code-block:: python 

854 

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

856 # code template only. 

857 # It will require modifications to work: 

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

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

860 # client as shown in: 

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

862 from google.cloud import logging_v2 

863 

864 async def sample_delete_log_metric(): 

865 # Create a client 

866 client = logging_v2.MetricsServiceV2AsyncClient() 

867 

868 # Initialize request argument(s) 

869 request = logging_v2.DeleteLogMetricRequest( 

870 metric_name="metric_name_value", 

871 ) 

872 

873 # Make the request 

874 await client.delete_log_metric(request=request) 

875 

876 Args: 

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

878 The request object. The parameters to DeleteLogMetric. 

879 metric_name (:class:`str`): 

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

881 

882 :: 

883 

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

885 

886 This corresponds to the ``metric_name`` field 

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

888 should not be set. 

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

890 should be retried. 

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

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

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

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

895 be of type `bytes`. 

896 """ 

897 # Create or coerce a protobuf request object. 

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

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

900 flattened_params = [metric_name] 

901 has_flattened_params = ( 

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

903 ) 

904 if request is not None and has_flattened_params: 

905 raise ValueError( 

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

907 "the individual field arguments should be set." 

908 ) 

909 

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

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

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

913 request = logging_metrics.DeleteLogMetricRequest(request) 

914 

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

916 # request, apply these. 

917 if metric_name is not None: 

918 request.metric_name = metric_name 

919 

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

921 # and friendly error handling. 

922 rpc = self._client._transport._wrapped_methods[ 

923 self._client._transport.delete_log_metric 

924 ] 

925 

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

927 # add these here. 

928 metadata = tuple(metadata) + ( 

929 gapic_v1.routing_header.to_grpc_metadata( 

930 (("metric_name", request.metric_name),) 

931 ), 

932 ) 

933 

934 # Validate the universe domain. 

935 self._client._validate_universe_domain() 

936 

937 # Send the request. 

938 await rpc( 

939 request, 

940 retry=retry, 

941 timeout=timeout, 

942 metadata=metadata, 

943 ) 

944 

945 async def list_operations( 

946 self, 

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

948 *, 

949 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

952 ) -> operations_pb2.ListOperationsResponse: 

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

954 

955 Args: 

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

957 The request object. Request message for 

958 `ListOperations` method. 

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

960 if any, should be retried. 

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

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

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

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

965 be of type `bytes`. 

966 Returns: 

967 ~.operations_pb2.ListOperationsResponse: 

968 Response message for ``ListOperations`` method. 

969 """ 

970 # Create or coerce a protobuf request object. 

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

972 # so it must be constructed via keyword expansion. 

973 if isinstance(request, dict): 

974 request = operations_pb2.ListOperationsRequest(**request) 

975 

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

977 # and friendly error handling. 

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

979 

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

981 # add these here. 

982 metadata = tuple(metadata) + ( 

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

984 ) 

985 

986 # Validate the universe domain. 

987 self._client._validate_universe_domain() 

988 

989 # Send the request. 

990 response = await rpc( 

991 request, 

992 retry=retry, 

993 timeout=timeout, 

994 metadata=metadata, 

995 ) 

996 

997 # Done; return the response. 

998 return response 

999 

1000 async def get_operation( 

1001 self, 

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

1003 *, 

1004 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1007 ) -> operations_pb2.Operation: 

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

1009 

1010 Args: 

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

1012 The request object. Request message for 

1013 `GetOperation` method. 

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

1015 if any, should be retried. 

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

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

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

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

1020 be of type `bytes`. 

1021 Returns: 

1022 ~.operations_pb2.Operation: 

1023 An ``Operation`` object. 

1024 """ 

1025 # Create or coerce a protobuf request object. 

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

1027 # so it must be constructed via keyword expansion. 

1028 if isinstance(request, dict): 

1029 request = operations_pb2.GetOperationRequest(**request) 

1030 

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

1032 # and friendly error handling. 

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

1034 

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

1036 # add these here. 

1037 metadata = tuple(metadata) + ( 

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

1039 ) 

1040 

1041 # Validate the universe domain. 

1042 self._client._validate_universe_domain() 

1043 

1044 # Send the request. 

1045 response = await rpc( 

1046 request, 

1047 retry=retry, 

1048 timeout=timeout, 

1049 metadata=metadata, 

1050 ) 

1051 

1052 # Done; return the response. 

1053 return response 

1054 

1055 async def cancel_operation( 

1056 self, 

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

1058 *, 

1059 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1062 ) -> None: 

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

1064 

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

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

1067 `google.rpc.Code.UNIMPLEMENTED`. 

1068 

1069 Args: 

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

1071 The request object. Request message for 

1072 `CancelOperation` method. 

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

1074 if any, should be retried. 

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

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

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

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

1079 be of type `bytes`. 

1080 Returns: 

1081 None 

1082 """ 

1083 # Create or coerce a protobuf request object. 

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

1085 # so it must be constructed via keyword expansion. 

1086 if isinstance(request, dict): 

1087 request = operations_pb2.CancelOperationRequest(**request) 

1088 

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

1090 # and friendly error handling. 

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

1092 

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

1094 # add these here. 

1095 metadata = tuple(metadata) + ( 

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

1097 ) 

1098 

1099 # Validate the universe domain. 

1100 self._client._validate_universe_domain() 

1101 

1102 # Send the request. 

1103 await rpc( 

1104 request, 

1105 retry=retry, 

1106 timeout=timeout, 

1107 metadata=metadata, 

1108 ) 

1109 

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

1111 return self 

1112 

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

1114 await self.transport.close() 

1115 

1116 

1117DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

1118 gapic_version=package_version.__version__ 

1119) 

1120 

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

1122 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

1123 

1124 

1125__all__ = ("MetricsServiceV2AsyncClient",)