Skip to content

Commit 45b63f9

Browse files
1 parent 54fc5dc commit 45b63f9

File tree

107 files changed

+1258
-23042
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

107 files changed

+1258
-23042
lines changed

‎google/cloud/errorreporting_v1beta1/services/error_group_service/async_client.py‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
#
16+
import logging as std_logging
1617
from collections import OrderedDict
1718
import re
1819
from typing import (
@@ -49,6 +50,15 @@
4950
from .transports.grpc_asyncio import ErrorGroupServiceGrpcAsyncIOTransport
5051
from .client import ErrorGroupServiceClient
5152

53+
try:
54+
from google.api_core import client_logging # type: ignore
55+
56+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
57+
except ImportError: # pragma: NO COVER
58+
CLIENT_LOGGING_SUPPORTED = False
59+
60+
_LOGGER = std_logging.getLogger(__name__)
61+
5262

5363
class ErrorGroupServiceAsyncClient:
5464
"""Service for retrieving and updating individual error groups."""
@@ -260,14 +270,36 @@ def __init__(
260270
client_info=client_info,
261271
)
262272

273+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
274+
std_logging.DEBUG
275+
): # pragma: NO COVER
276+
_LOGGER.debug(
277+
"Created client `google.devtools.clouderrorreporting_v1beta1.ErrorGroupServiceAsyncClient`.",
278+
extra={
279+
"serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
280+
"universeDomain": getattr(
281+
self._client._transport._credentials, "universe_domain", ""
282+
),
283+
"credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
284+
"credentialsInfo": getattr(
285+
self.transport._credentials, "get_cred_info", lambda: None
286+
)(),
287+
}
288+
if hasattr(self._client._transport, "_credentials")
289+
else {
290+
"serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
291+
"credentialsType": None,
292+
},
293+
)
294+
263295
async def get_group(
264296
self,
265297
request: Optional[Union[error_group_service.GetGroupRequest, dict]] = None,
266298
*,
267299
group_name: Optional[str] = None,
268300
retry: OptionalRetry = gapic_v1.method.DEFAULT,
269301
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
270-
metadata: Sequence[Tuple[str, str]] = (),
302+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
271303
) -> common.ErrorGroup:
272304
r"""Get the specified group.
273305
@@ -329,8 +361,10 @@ async def sample_get_group():
329361
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
330362
should be retried.
331363
timeout (float): The timeout for this request.
332-
metadata (Sequence[Tuple[str, str]]): Strings which should be
333-
sent along with the request as metadata.
364+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
365+
sent along with the request as metadata. Normally, each value must be of type `str`,
366+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
367+
be of type `bytes`.
334368
335369
Returns:
336370
google.cloud.errorreporting_v1beta1.types.ErrorGroup:
@@ -393,7 +427,7 @@ async def update_group(
393427
group: Optional[common.ErrorGroup] = None,
394428
retry: OptionalRetry = gapic_v1.method.DEFAULT,
395429
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
396-
metadata: Sequence[Tuple[str, str]] = (),
430+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
397431
) -> common.ErrorGroup:
398432
r"""Replace the data for the specified group.
399433
Fails if the group does not exist.
@@ -437,8 +471,10 @@ async def sample_update_group():
437471
retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
438472
should be retried.
439473
timeout (float): The timeout for this request.
440-
metadata (Sequence[Tuple[str, str]]): Strings which should be
441-
sent along with the request as metadata.
474+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
475+
sent along with the request as metadata. Normally, each value must be of type `str`,
476+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
477+
be of type `bytes`.
442478
443479
Returns:
444480
google.cloud.errorreporting_v1beta1.types.ErrorGroup:

‎google/cloud/errorreporting_v1beta1/services/error_group_service/client.py‎

Lines changed: 47 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515
#
1616
from collections import OrderedDict
17+
import logging as std_logging
1718
import os
1819
import re
1920
from typing import (
@@ -48,6 +49,15 @@
4849
except AttributeError: # pragma: NO COVER
4950
OptionalRetry = Union[retries.Retry, object, None] # type: ignore
5051

52+
try:
53+
from google.api_core import client_logging # type: ignore
54+
55+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
56+
except ImportError: # pragma: NO COVER
57+
CLIENT_LOGGING_SUPPORTED = False
58+
59+
_LOGGER = std_logging.getLogger(__name__)
60+
5161
from google.cloud.errorreporting_v1beta1.types import common
5262
from google.cloud.errorreporting_v1beta1.types import error_group_service
5363
from .transports.base import ErrorGroupServiceTransport, DEFAULT_CLIENT_INFO
@@ -576,6 +586,10 @@ def __init__(
576586
# Initialize the universe domain validation.
577587
self._is_universe_domain_valid = False
578588

589+
if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
590+
# Setup logging.
591+
client_logging.initialize_logging()
592+
579593
api_key_value = getattr(self._client_options, "api_key", None)
580594
if api_key_value and credentials:
581595
raise ValueError(
@@ -642,14 +656,37 @@ def __init__(
642656
api_audience=self._client_options.api_audience,
643657
)
644658

659+
if "async" not in str(self._transport):
660+
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
661+
std_logging.DEBUG
662+
): # pragma: NO COVER
663+
_LOGGER.debug(
664+
"Created client `google.devtools.clouderrorreporting_v1beta1.ErrorGroupServiceClient`.",
665+
extra={
666+
"serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
667+
"universeDomain": getattr(
668+
self._transport._credentials, "universe_domain", ""
669+
),
670+
"credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
671+
"credentialsInfo": getattr(
672+
self.transport._credentials, "get_cred_info", lambda: None
673+
)(),
674+
}
675+
if hasattr(self._transport, "_credentials")
676+
else {
677+
"serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
678+
"credentialsType": None,
679+
},
680+
)
681+
645682
def get_group(
646683
self,
647684
request: Optional[Union[error_group_service.GetGroupRequest, dict]] = None,
648685
*,
649686
group_name: Optional[str] = None,
650687
retry: OptionalRetry = gapic_v1.method.DEFAULT,
651688
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
652-
metadata: Sequence[Tuple[str, str]] = (),
689+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
653690
) -> common.ErrorGroup:
654691
r"""Get the specified group.
655692
@@ -711,8 +748,10 @@ def sample_get_group():
711748
retry (google.api_core.retry.Retry): Designation of what errors, if any,
712749
should be retried.
713750
timeout (float): The timeout for this request.
714-
metadata (Sequence[Tuple[str, str]]): Strings which should be
715-
sent along with the request as metadata.
751+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
752+
sent along with the request as metadata. Normally, each value must be of type `str`,
753+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
754+
be of type `bytes`.
716755
717756
Returns:
718757
google.cloud.errorreporting_v1beta1.types.ErrorGroup:
@@ -772,7 +811,7 @@ def update_group(
772811
group: Optional[common.ErrorGroup] = None,
773812
retry: OptionalRetry = gapic_v1.method.DEFAULT,
774813
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
775-
metadata: Sequence[Tuple[str, str]] = (),
814+
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
776815
) -> common.ErrorGroup:
777816
r"""Replace the data for the specified group.
778817
Fails if the group does not exist.
@@ -816,8 +855,10 @@ def sample_update_group():
816855
retry (google.api_core.retry.Retry): Designation of what errors, if any,
817856
should be retried.
818857
timeout (float): The timeout for this request.
819-
metadata (Sequence[Tuple[str, str]]): Strings which should be
820-
sent along with the request as metadata.
858+
metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
859+
sent along with the request as metadata. Normally, each value must be of type `str`,
860+
but for metadata keys ending with the suffix `-bin`, the corresponding values must
861+
be of type `bytes`.
821862
822863
Returns:
823864
google.cloud.errorreporting_v1beta1.types.ErrorGroup:

‎google/cloud/errorreporting_v1beta1/services/error_group_service/transports/grpc.py‎

Lines changed: 90 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
#
16+
import json
17+
import logging as std_logging
18+
import pickle
1619
import warnings
1720
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
1821

@@ -21,13 +24,91 @@
2124
import google.auth # type: ignore
2225
from google.auth import credentials as ga_credentials # type: ignore
2326
from google.auth.transport.grpc import SslCredentials # type: ignore
27+
from google.protobuf.json_format import MessageToJson
28+
import google.protobuf.message
2429

2530
import grpc # type: ignore
31+
import proto # type: ignore
2632

2733
from google.cloud.errorreporting_v1beta1.types import common
2834
from google.cloud.errorreporting_v1beta1.types import error_group_service
2935
from .base import ErrorGroupServiceTransport, DEFAULT_CLIENT_INFO
3036

37+
try:
38+
from google.api_core import client_logging # type: ignore
39+
40+
CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
41+
except ImportError: # pragma: NO COVER
42+
CLIENT_LOGGING_SUPPORTED = False
43+
44+
_LOGGER = std_logging.getLogger(__name__)
45+
46+
47+
class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
48+
def intercept_unary_unary(self, continuation, client_call_details, request):
49+
logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
50+
std_logging.DEBUG
51+
)
52+
if logging_enabled: # pragma: NO COVER
53+
request_metadata = client_call_details.metadata
54+
if isinstance(request, proto.Message):
55+
request_payload = type(request).to_json(request)
56+
elif isinstance(request, google.protobuf.message.Message):
57+
request_payload = MessageToJson(request)
58+
else:
59+
request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
60+
61+
request_metadata = {
62+
key: value.decode("utf-8") if isinstance(value, bytes) else value
63+
for key, value in request_metadata
64+
}
65+
grpc_request = {
66+
"payload": request_payload,
67+
"requestMethod": "grpc",
68+
"metadata": dict(request_metadata),
69+
}
70+
_LOGGER.debug(
71+
f"Sending request for {client_call_details.method}",
72+
extra={
73+
"serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
74+
"rpcName": client_call_details.method,
75+
"request": grpc_request,
76+
"metadata": grpc_request["metadata"],
77+
},
78+
)
79+
80+
response = continuation(client_call_details, request)
81+
if logging_enabled: # pragma: NO COVER
82+
response_metadata = response.trailing_metadata()
83+
# Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
84+
metadata = (
85+
dict([(k, str(v)) for k, v in response_metadata])
86+
if response_metadata
87+
else None
88+
)
89+
result = response.result()
90+
if isinstance(result, proto.Message):
91+
response_payload = type(result).to_json(result)
92+
elif isinstance(result, google.protobuf.message.Message):
93+
response_payload = MessageToJson(result)
94+
else:
95+
response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
96+
grpc_response = {
97+
"payload": response_payload,
98+
"metadata": metadata,
99+
"status": "OK",
100+
}
101+
_LOGGER.debug(
102+
f"Received response for {client_call_details.method}.",
103+
extra={
104+
"serviceName": "google.devtools.clouderrorreporting.v1beta1.ErrorGroupService",
105+
"rpcName": client_call_details.method,
106+
"response": grpc_response,
107+
"metadata": grpc_response["metadata"],
108+
},
109+
)
110+
return response
111+
31112

32113
class ErrorGroupServiceGrpcTransport(ErrorGroupServiceTransport):
33114
"""gRPC backend transport for ErrorGroupService.
@@ -181,7 +262,12 @@ def __init__(
181262
],
182263
)
183264

184-
# Wrap messages. This must be done after self._grpc_channel exists
265+
self._interceptor = _LoggingClientInterceptor()
266+
self._logged_channel = grpc.intercept_channel(
267+
self._grpc_channel, self._interceptor
268+
)
269+
270+
# Wrap messages. This must be done after self._logged_channel exists
185271
self._prep_wrapped_messages(client_info)
186272

187273
@classmethod
@@ -255,7 +341,7 @@ def get_group(
255341
# gRPC handles serialization and deserialization, so we just need
256342
# to pass in the functions for each.
257343
if "get_group" not in self._stubs:
258-
self._stubs["get_group"] = self.grpc_channel.unary_unary(
344+
self._stubs["get_group"] = self._logged_channel.unary_unary(
259345
"/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/GetGroup",
260346
request_serializer=error_group_service.GetGroupRequest.serialize,
261347
response_deserializer=common.ErrorGroup.deserialize,
@@ -282,15 +368,15 @@ def update_group(
282368
# gRPC handles serialization and deserialization, so we just need
283369
# to pass in the functions for each.
284370
if "update_group" not in self._stubs:
285-
self._stubs["update_group"] = self.grpc_channel.unary_unary(
371+
self._stubs["update_group"] = self._logged_channel.unary_unary(
286372
"/google.devtools.clouderrorreporting.v1beta1.ErrorGroupService/UpdateGroup",
287373
request_serializer=error_group_service.UpdateGroupRequest.serialize,
288374
response_deserializer=common.ErrorGroup.deserialize,
289375
)
290376
return self._stubs["update_group"]
291377

292378
def close(self):
293-
self.grpc_channel.close()
379+
self._logged_channel.close()
294380

295381
@property
296382
def kind(self) -> str:

0 commit comments

Comments
 (0)