Skip to content

Commit 77220ed

Browse files
author
wallisyan
committed
global settings;auth add logger; retry add logger
modify retry_condition.py modify logger infomations modify lint
1 parent dbdb963 commit 77220ed

File tree

10 files changed

+76
-24
lines changed

10 files changed

+76
-24
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,4 @@
11
__version__ = "2.12.1"
22

3+
import logging
4+
logging.getLogger('aliyunsdkcore').addHandler(logging.NullHandler())

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/access_key_signer.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,18 @@
1919
# specific language governing permissions and limitations
2020
# under the License.
2121

22+
import logging
2223
from aliyunsdkcore.auth.signers.signer import Signer
2324

25+
logger = logging.getLogger(__name__)
26+
2427

2528
class AccessKeySigner(Signer):
2629
def __init__(self, access_key_credential):
2730
self._credential = access_key_credential
2831

2932
def sign(self, region_id, request):
33+
logger.debug("Calculating signature using AccessKey.")
3034
cred = self._credential
3135
header = request.get_signed_header(region_id, cred.access_key_id, cred.access_key_secret)
3236
url = request.get_url(region_id, cred.access_key_id, cred.access_key_secret)

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/ecs_ram_role_signer.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,14 @@
2020
# under the License.
2121

2222
import time
23-
23+
import logging
24+
import json
2425

2526
from aliyunsdkcore.vendored.six.moves.urllib.request import urlopen
26-
2727
from aliyunsdkcore.auth.signers.signer import Signer
2828
from aliyunsdkcore.acs_exception.exceptions import ServerException
2929

30-
import json
30+
logger = logging.getLogger(__name__)
3131

3232

3333
class EcsRamRoleSigner(Signer):
@@ -39,6 +39,7 @@ def __init__(self, ecs_ram_role_credential):
3939
self._expiration = 0
4040

4141
def sign(self, region_id, request):
42+
logger.debug("Calculating signature using EcsRamRole.")
4243
self._check_session_credential()
4344
session_ak, session_sk, token = self._session_credential
4445
if request.get_style() == 'RPC':

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/ram_role_arn_signer.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
import time
2323
import json
24+
import logging
2425

2526
from aliyunsdkcore.auth.signers.signer import Signer
2627
from aliyunsdkcore.auth.signers.access_key_signer import AccessKeySigner
@@ -31,6 +32,8 @@
3132
from aliyunsdkcore.request import CommonRequest
3233
from aliyunsdkcore.compat import ensure_string
3334

35+
logger = logging.getLogger(__name__)
36+
3437

3538
class RamRoleArnSigner(Signer):
3639
_SESSION_PERIOD = 3600
@@ -47,6 +50,7 @@ def __init__(self, credential, do_action_api):
4750
self._credential.session_role_name = "aliyun-python-sdk-" + str(time.time())
4851

4952
def sign(self, region_id, request):
53+
logger.debug("Calculating signature using RamRoleArn.")
5054
self._check_session_credential()
5155
session_ak, session_sk, token = self._session_credential
5256
if request.get_style() == 'RPC':

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/rsa_key_pair_signer.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
from aliyunsdkcore.request import RpcRequest
1212
from aliyunsdkcore.auth.algorithm import sha_hmac256
1313

14+
logger = logging.getLogger(__name__)
15+
1416

1517
class RsaKeyPairSigner(Signer):
1618
_MIN_SESSION_PERIOD = 900
@@ -37,6 +39,7 @@ def __init__(self, credential, region_id, debug=False):
3739
self._session_credential = None
3840

3941
def sign(self, region_id, request):
42+
logger.debug("Calculating signature using RsaKeyPair.")
4043
self._check_session_credential()
4144
session_ak, session_sk = self._session_credential
4245
header = request.get_signed_header(region_id, session_ak, session_sk)

aliyun-python-sdk-core/aliyunsdkcore/auth/signers/sts_token_signer.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,19 @@
1919
# specific language governing permissions and limitations
2020
# under the License.
2121

22+
import logging
23+
2224
from aliyunsdkcore.auth.signers.signer import Signer
2325

26+
logger = logging.getLogger(__name__)
27+
2428

2529
class StsTokenSigner(Signer):
2630
def __init__(self, sts_credential):
2731
self._credential = sts_credential
2832

2933
def sign(self, region_id, request):
34+
logger.debug("Calculating signature using StsToken.")
3035
sts_cred = self._credential
3136
if request.get_style() == 'RPC':
3237
request.add_query_param("SecurityToken", sts_cred.sts_token)

aliyun-python-sdk-core/aliyunsdkcore/client.py

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@
2121
import time
2222
import warnings
2323
import json
24-
import aliyunsdkcore
24+
import logging
2525
import jmespath
26+
27+
import aliyunsdkcore
2628
from aliyunsdkcore.vendored.six.moves.urllib.parse import urlencode
2729
from aliyunsdkcore.vendored.requests import codes
2830

@@ -53,8 +55,11 @@
5355
# TODO: replace it with TimeoutHandler
5456
_api_timeout_config_data = aliyunsdkcore.utils._load_json_from_data_dir("timeout_config.json")
5557

58+
logger = logging.getLogger(__name__)
59+
5660

5761
class AcsClient:
62+
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
5863

5964
def __init__(
6065
self,
@@ -253,7 +258,6 @@ def _handle_retry_and_timeout(self, endpoint, request, signer):
253258

254259
request_timeout = self._get_request_timeout(request)
255260

256-
retryable = RetryCondition.SHOULD_RETRY
257261
retries = 0
258262

259263
while True:
@@ -266,8 +270,10 @@ def _handle_retry_and_timeout(self, endpoint, request, signer):
266270
retryable = self._retry_policy.should_retry(retry_policy_context)
267271
if retryable & RetryCondition.NO_RETRY:
268272
break
273+
logger.debug("Retry needed, request is: %s", request.get_action_name())
269274
retry_policy_context.retryable = retryable
270275
time_to_sleep = self._retry_policy.compute_delay_before_next_retry(retry_policy_context)
276+
logger.debug('Retry %s times', retries)
271277
time.sleep(time_to_sleep / 1000.0)
272278
retries += 1
273279

@@ -278,20 +284,18 @@ def _handle_retry_and_timeout(self, endpoint, request, signer):
278284

279285
def _handle_single_request(self, endpoint, request, timeout, signer):
280286
http_response = self._make_http_response(endpoint, request, timeout, signer)
281-
282-
exception = None
287+
params = request.get_query_params()
288+
params.pop('AccessKeyId', None)
289+
logger.debug('The request params are %s', str(params))
283290

284291
# Do the actual network thing
285292
try:
286293
status, headers, body = http_response.get_response_object()
287294
except IOError as e:
288295
error_message = str(e)
289296
error_message += "\nEndpoint: " + endpoint
290-
error_message += "\nProduct: " + str(request.get_product())
291-
error_message += "\nSdkCoreVersion: " + aliyunsdkcore.__version__
292-
error_message += "\nHttpUrl: " + str(http_response.get_url())
293-
error_message += "\nHttpHeaders: " + \
294-
str(http_response.get_headers())
297+
logger.error('Catch a HttpError when connect to %s, current sdk version is %s',
298+
endpoint, aliyunsdkcore.__version__, exc_info=True)
295299

296300
exception = ClientException(error_code.SDK_HTTP_ERROR, error_message)
297301
return None, None, None, exception
@@ -312,7 +316,7 @@ def _parse_error_info_from_response_body(response_body):
312316
error_message_to_return = body_obj['Message']
313317
except ValueError:
314318
# failed to parse body as json format
315-
pass
319+
logger.warning('failed to parse response body as json format')
316320

317321
return error_code_to_return, error_message_to_return
318322

@@ -325,7 +329,7 @@ def _get_server_exception(self, http_status, response_body):
325329
except (ValueError, TypeError, AttributeError):
326330
# in case the response body is not a json string, return the raw
327331
# data instead
328-
pass
332+
logger.warning('failed to parse response body as json format')
329333

330334
if http_status < codes.OK or http_status >= codes.MULTIPLE_CHOICES:
331335

@@ -372,3 +376,25 @@ def get_response(self, acs_request):
372376
def add_endpoint(self, region_id, product_code, endpoint):
373377
self._endpoint_resolver.put_endpoint_entry(
374378
region_id, product_code, endpoint)
379+
380+
def set_stream_logger(self, log_level=logging.INFO, logger_name='aliyunsdkcore', stream=None,
381+
format_string=None):
382+
log = logging.getLogger(logger_name)
383+
log.setLevel(log_level)
384+
ch = logging.StreamHandler(stream)
385+
ch.setLevel(log_level)
386+
if format_string is None:
387+
format_string = self.LOG_FORMAT
388+
formatter = logging.Formatter(format_string)
389+
ch.setFormatter(formatter)
390+
log.addHandler(ch)
391+
392+
def set_file_logger(self, path, log_level=logging.INFO, logger_name='aliyunsdkcore'):
393+
log = logging.getLogger(logger_name)
394+
log.setLevel(log_level)
395+
fh = logging.FileHandler(path)
396+
fh.setLevel(log_level)
397+
formatter = logging.Formatter(self.LOG_FORMAT)
398+
fh.setFormatter(formatter)
399+
log.addHandler(fh)
400+

aliyun-python-sdk-core/aliyunsdkcore/retry/retry_condition.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,15 @@
1313
# limitations under the License.
1414

1515
import jmespath
16+
import logging
1617

1718
import aliyunsdkcore.utils
1819
import aliyunsdkcore.utils.validation as validation
1920
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
2021
import aliyunsdkcore.acs_exception.error_code as error_code
2122

23+
logger = logging.getLogger(__name__)
24+
2225

2326
def _find_data_in_retry_config(key_name, request, retry_config):
2427
if request.get_product() is None:
@@ -55,9 +58,12 @@ def __init__(self, max_retry_times):
5558
self.max_retry_times = max_retry_times
5659

5760
def should_retry(self, retry_policy_context):
61+
5862
if retry_policy_context.retries_attempted < self.max_retry_times:
5963
return RetryCondition.SHOULD_RETRY
6064
else:
65+
logger.debug("Reached the maximum number of retry "
66+
"attempts: %s", retry_policy_context.retries_attempted)
6167
return RetryCondition.NO_RETRY
6268

6369

@@ -72,6 +78,8 @@ def should_retry(self, retry_policy_context):
7278

7379
if isinstance(exception, ClientException):
7480
if exception.get_error_code() == error_code.SDK_HTTP_ERROR:
81+
logger.debug("Retry needed, retryable ClientException caught: %s",
82+
exception, exc_info=True)
7583
return RetryCondition.SHOULD_RETRY
7684

7785
if isinstance(exception, ServerException):
@@ -80,14 +88,18 @@ def should_retry(self, retry_policy_context):
8088
request,
8189
self.retry_config)
8290
if isinstance(normal_errors, list) and error_code_ in normal_errors:
91+
logger.debug("Retry needed, retryable ServerException caught: %s",
92+
exception, exc_info=True)
8393
return RetryCondition.SHOULD_RETRY
8494

8595
throttling_errors = _find_data_in_retry_config("RetryableThrottlingErrors",
8696
request,
8797
self.retry_config)
8898
if isinstance(throttling_errors, list) and error_code_ in throttling_errors:
99+
logger.debug("Retry needed, retryable ThrottlingError caught: %s",
100+
exception, exc_info=True)
89101
return RetryCondition.SHOULD_RETRY | \
90-
RetryCondition.SHOULD_RETRY_WITH_THROTTLING_BACKOFF
102+
RetryCondition.SHOULD_RETRY_WITH_THROTTLING_BACKOFF
91103

92104
return RetryCondition.NO_RETRY
93105

@@ -106,6 +118,9 @@ def __init__(self, retryable_http_status_list=None):
106118

107119
def should_retry(self, retry_policy_context):
108120
if retry_policy_context.http_status_code in self.retryable_http_status_list:
121+
logger.debug(
122+
"Retry needed: retryable HTTP status code received: %s",
123+
retry_policy_context.http_status_code)
109124
return RetryCondition.SHOULD_RETRY
110125
else:
111126
return RetryCondition.NO_RETRY

python-sdk-functional-test/credentials_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def test_call_roa_request_with_sts_token(self):
7878
def test_ecs_ram_role(self):
7979
# push ecs
8080
from aliyunsdkcore.auth.credentials import EcsRamRoleCredential
81-
ecs_ram_role_credential = EcsRamRoleCredential("TestRole")
81+
ecs_ram_role_credential = EcsRamRoleCredential("EcsRamRoleTest")
8282
acs_client = AcsClient(region_id="cn-hangzhou", credential=ecs_ram_role_credential)
8383
request = DescribeRegionsRequest()
8484
response = acs_client.do_action_with_exception(request)

python-sdk-functional-test/error_handle_test.py

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,6 @@ def test_server_timeout(self):
3636
self.assertEqual("SDK.HttpError", e.error_code)
3737
head_message, attributes = self._parse_complex_error_message(e.get_error_msg())
3838
self.assertEqual("ecs-cn-hangzhou.aliyuncs.com", attributes.get("Endpoint"))
39-
self.assertEqual("Ecs", attributes.get("Product"))
40-
self.assertTrue("SdkCoreVersion" in attributes)
41-
self.assertTrue("HttpUrl" in attributes)
42-
self.assertTrue("HttpHeaders" in attributes)
4339

4440
def test_server_unreachable(self):
4541
from aliyunsdkcore.request import CommonRequest
@@ -52,10 +48,6 @@ def test_server_unreachable(self):
5248
self.assertEqual("SDK.HttpError", e.error_code)
5349
head_message, attributes = self._parse_complex_error_message(e.get_error_msg())
5450
self.assertEqual("www.aliyun-hangzhou.com", attributes.get("Endpoint"))
55-
self.assertEqual("None", attributes.get("Product"))
56-
self.assertTrue("SdkCoreVersion" in attributes)
57-
self.assertTrue("HttpUrl" in attributes)
58-
self.assertTrue("HttpHeaders" in attributes)
5951

6052
def test_server_error_normal(self):
6153
from aliyunsdkecs.request.v20140526.DeleteInstanceRequest import DeleteInstanceRequest

0 commit comments

Comments
 (0)