From ccceffa7f56bfcc2ff42f98a6272ace866993d09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A1bor=20Antal?= Date: Tue, 7 Feb 2017 17:54:11 +0100 Subject: [PATCH] Handle log message interpolation by the logger According to OpenStack Guideline[1], logged string message should be interpolated by the logger. Also, upgraded hacking requirement, to enable H904 check. [1]: http://docs.openstack.org/developer/oslo.i18n/guidelines.html#adding-variables-to-log-messages Co-Authored-By: jiansong Change-Id: I3f020b6bcb1b9bf6d18a3b4f738c13cccd1bbff8 Closes-Bug: #1596829 --- tox.ini | 1 + troveclient/apiclient/client.py | 12 ++++++------ troveclient/auth_plugin.py | 6 +++--- troveclient/client.py | 24 ++++++++++++------------ troveclient/compat/client.py | 28 ++++++++++++++-------------- troveclient/shell.py | 4 ++-- 6 files changed, 38 insertions(+), 37 deletions(-) diff --git a/tox.ini b/tox.ini index a3291430..de4f1a34 100644 --- a/tox.ini +++ b/tox.ini @@ -57,6 +57,7 @@ commands = commands = sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html [flake8] +enable-extensions = H106,H203,H904 ignore = H202,H405,H501 show-source = True exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build,releasenotes diff --git a/troveclient/apiclient/client.py b/troveclient/apiclient/client.py index a94f46d4..ee15e5b9 100644 --- a/troveclient/apiclient/client.py +++ b/troveclient/apiclient/client.py @@ -39,7 +39,7 @@ from oslo_utils import importutils from troveclient.apiclient import exceptions -_logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) class HTTPClient(object): @@ -111,19 +111,19 @@ class HTTPClient(object): header = "-H '%s: %s'" % (element, kwargs['headers'][element]) string_parts.append(header) - _logger.debug("REQ: %s" % " ".join(string_parts)) + LOG.debug("REQ: %s", " ".join(string_parts)) if 'data' in kwargs: - _logger.debug("REQ BODY: %s\n" % (kwargs['data'])) + LOG.debug("REQ BODY: %s\n", kwargs['data']) def _http_log_resp(self, resp): if not self.debug: return - _logger.debug( + LOG.debug( "RESP: [%s] %s\n", resp.status_code, resp.headers) if resp._content_consumed: - _logger.debug( + LOG.debug( "RESP BODY: %s\n", resp.text) @@ -176,7 +176,7 @@ class HTTPClient(object): self._http_log_resp(resp) if resp.status_code >= 400: - _logger.debug( + LOG.debug( "Request returned failure status: %s", resp.status_code) raise exceptions.from_response(resp, method, url) diff --git a/troveclient/auth_plugin.py b/troveclient/auth_plugin.py index 7811d063..bc6d9b4d 100644 --- a/troveclient/auth_plugin.py +++ b/troveclient/auth_plugin.py @@ -24,7 +24,7 @@ from troveclient._i18n import _ from troveclient import exceptions -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) _discovered_plugins = {} @@ -40,8 +40,8 @@ def discover_auth_systems(): try: auth_plugin = ep.load() except (ImportError, pkg_resources.UnknownExtra, AttributeError) as e: - logger.debug(_("ERROR: Cannot load auth plugin %s") % ep.name) - logger.debug(e, exc_info=1) + LOG.debug(_("ERROR: Cannot load auth plugin %s"), ep.name) + LOG.debug(e, exc_info=1) else: _discovered_plugins[ep.name] = auth_plugin diff --git a/troveclient/client.py b/troveclient/client.py index a0a67ae5..a6f97eab 100644 --- a/troveclient/client.py +++ b/troveclient/client.py @@ -119,11 +119,11 @@ class HTTPClient(TroveClientMixin): self.auth_system = auth_system self.auth_plugin = auth_plugin - self._logger = logging.getLogger(__name__) - if self.http_log_debug and not self._logger.handlers: + self.LOG = logging.getLogger(__name__) + if self.http_log_debug and not self.LOG.handlers: ch = logging.StreamHandler() - self._logger.setLevel(logging.DEBUG) - self._logger.addHandler(ch) + self.LOG.setLevel(logging.DEBUG) + self.LOG.addHandler(ch) if hasattr(requests, 'logging'): requests.logging.getLogger(requests.__name__).addHandler(ch) @@ -144,12 +144,12 @@ class HTTPClient(TroveClientMixin): if 'data' in kwargs: string_parts.append(" -d '%s'" % (kwargs['data'])) - self._logger.debug("\nREQ: %s\n" % "".join(string_parts)) + self.LOG.debug("\nREQ: %s\n", "".join(string_parts)) def http_log_resp(self, resp): if not self.http_log_debug: return - self._logger.debug( + self.LOG.debug( "RESP: [%s] %s\nRESP BODY: %s\n", resp.status_code, resp.headers, @@ -211,7 +211,7 @@ class HTTPClient(TroveClientMixin): except exceptions.Unauthorized: if auth_attempts > 0: raise - self._logger.debug("Unauthorized, reauthenticating.") + self.LOG.debug("Unauthorized, reauthenticating.") self.management_url = self.auth_token = None # First reauth. Discount this attempt. attempts -= 1 @@ -226,12 +226,12 @@ class HTTPClient(TroveClientMixin): raise except requests.exceptions.ConnectionError as e: # Catch a connection refused from requests.request - self._logger.debug("Connection refused: %s" % e) + self.LOG.debug("Connection refused: %s", e) msg = 'Unable to establish connection: %s' % e raise exceptions.ConnectionRefused(msg) - self._logger.debug( - "Failed attempt(%s of %s), retrying in %s seconds" % - (attempts, self.retries, backoff)) + self.LOG.debug( + "Failed attempt(%s of %s), retrying in %s seconds", + attempts, self.retries, backoff) sleep_lib.sleep(backoff) backoff *= 2 @@ -303,7 +303,7 @@ class HTTPClient(TroveClientMixin): # GET ...:5001/v2.0/tokens/#####/endpoints url = '/'.join([url, 'tokens', '%s?belongsTo=%s' % (self.proxy_token, self.proxy_tenant_id)]) - self._logger.debug("Using Endpoint URL: %s" % url) + self.LOG.debug("Using Endpoint URL: %s", url) resp, body = self.request(url, "GET", headers={'X-Auth-Token': self.auth_token}) return self._extract_service_catalog(url, resp, body, diff --git a/troveclient/compat/client.py b/troveclient/compat/client.py index 7885c9b2..b528d697 100644 --- a/troveclient/compat/client.py +++ b/troveclient/compat/client.py @@ -29,7 +29,7 @@ from troveclient.compat import auth from troveclient.compat import exceptions -_logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) RDC_PP = os.environ.get("RDC_PP", "False") == "True" @@ -39,8 +39,8 @@ expected_errors = (400, 401, 403, 404, 408, 409, 413, 422, 500, 501) def log_to_streamhandler(stream=None): stream = stream or sys.stderr ch = logging.StreamHandler(stream) - _logger.setLevel(logging.DEBUG) - _logger.addHandler(ch) + LOG.setLevel(logging.DEBUG) + LOG.addHandler(ch) if 'REDDWARFCLIENT_DEBUG' in os.environ and os.environ['REDDWARFCLIENT_DEBUG']: @@ -105,7 +105,7 @@ class TroveHTTPClient(httplib2.Http): self.pretty_log(args, kwargs, resp, body) def simple_log(self, args, kwargs, resp, body): - if not _logger.isEnabledFor(logging.DEBUG): + if not LOG.isEnabledFor(logging.DEBUG): return string_parts = ['curl -i'] @@ -119,13 +119,13 @@ class TroveHTTPClient(httplib2.Http): header = ' -H "%s: %s"' % (element, kwargs['headers'][element]) string_parts.append(header) - _logger.debug("REQ: %s\n" % "".join(string_parts)) + LOG.debug("REQ: %s\n", "".join(string_parts)) if 'body' in kwargs: - _logger.debug("REQ BODY: %s\n" % (kwargs['body'])) - _logger.debug("RESP:%s %s\n", resp, body) + LOG.debug("REQ BODY: %s\n", kwargs['body']) + LOG.debug("RESP:%s %s\n", resp, body) def pretty_log(self, args, kwargs, resp, body): - if not _logger.isEnabledFor(logging.DEBUG): + if not LOG.isEnabledFor(logging.DEBUG): return string_parts = ['curl -i'] @@ -140,24 +140,24 @@ class TroveHTTPClient(httplib2.Http): string_parts.append(header) curl_cmd = "".join(string_parts) - _logger.debug("REQUEST:") + LOG.debug("REQUEST:") if 'body' in kwargs: - _logger.debug("%s -d '%s'" % (curl_cmd, kwargs['body'])) + LOG.debug("%s -d '%s'", curl_cmd, kwargs['body']) try: req_body = json.dumps(json.loads(kwargs['body']), sort_keys=True, indent=4) except Exception: req_body = kwargs['body'] - _logger.debug("BODY: %s\n" % (req_body)) + LOG.debug("BODY: %s\n", req_body) else: - _logger.debug(curl_cmd) + LOG.debug(curl_cmd) try: resp_body = json.dumps(json.loads(body), sort_keys=True, indent=4) except Exception: resp_body = body - _logger.debug("RESPONSE HEADERS: %s" % resp) - _logger.debug("RESPONSE BODY : %s" % resp_body) + LOG.debug("RESPONSE HEADERS: %s", resp) + LOG.debug("RESPONSE BODY : %s", resp_body) def request(self, *args, **kwargs): kwargs.setdefault('headers', kwargs.get('headers', {})) diff --git a/troveclient/shell.py b/troveclient/shell.py index 0466f372..29c9228b 100644 --- a/troveclient/shell.py +++ b/troveclient/shell.py @@ -51,7 +51,7 @@ DEFAULT_OS_DATABASE_API_VERSION = "1.0" DEFAULT_TROVE_ENDPOINT_TYPE = 'publicURL' DEFAULT_TROVE_SERVICE_TYPE = 'database' -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) osprofiler_profiler = importutils.try_import("osprofiler.profiler") @@ -751,7 +751,7 @@ def main(): print(_("... terminating trove client"), file=sys.stderr) sys.exit(130) except Exception as e: - logger.debug(e, exc_info=1) + LOG.debug(e, exc_info=1) message = six.text_type(e) if not isinstance(message, six.string_types): message = str(message)