Browse Source

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 <jian.song@easystack.cn>
Change-Id: I3f020b6bcb1b9bf6d18a3b4f738c13cccd1bbff8
Closes-Bug: #1596829
tags/2.11.0
Gábor Antal 2 years ago
parent
commit
ccceffa7f5
6 changed files with 38 additions and 37 deletions
  1. 1
    0
      tox.ini
  2. 6
    6
      troveclient/apiclient/client.py
  3. 3
    3
      troveclient/auth_plugin.py
  4. 12
    12
      troveclient/client.py
  5. 14
    14
      troveclient/compat/client.py
  6. 2
    2
      troveclient/shell.py

+ 1
- 0
tox.ini View File

@@ -57,6 +57,7 @@ commands =
57 57
 commands = sphinx-build -a -E -W -d releasenotes/build/doctrees -b html releasenotes/source releasenotes/build/html
58 58
 
59 59
 [flake8]
60
+enable-extensions = H106,H203,H904
60 61
 ignore = H202,H405,H501
61 62
 show-source = True
62 63
 exclude=.venv,.git,.tox,dist,doc,*lib/python*,*egg,build,releasenotes

+ 6
- 6
troveclient/apiclient/client.py View File

@@ -39,7 +39,7 @@ from oslo_utils import importutils
39 39
 from troveclient.apiclient import exceptions
40 40
 
41 41
 
42
-_logger = logging.getLogger(__name__)
42
+LOG = logging.getLogger(__name__)
43 43
 
44 44
 
45 45
 class HTTPClient(object):
@@ -111,19 +111,19 @@ class HTTPClient(object):
111 111
             header = "-H '%s: %s'" % (element, kwargs['headers'][element])
112 112
             string_parts.append(header)
113 113
 
114
-        _logger.debug("REQ: %s" % " ".join(string_parts))
114
+        LOG.debug("REQ: %s", " ".join(string_parts))
115 115
         if 'data' in kwargs:
116
-            _logger.debug("REQ BODY: %s\n" % (kwargs['data']))
116
+            LOG.debug("REQ BODY: %s\n", kwargs['data'])
117 117
 
118 118
     def _http_log_resp(self, resp):
119 119
         if not self.debug:
120 120
             return
121
-        _logger.debug(
121
+        LOG.debug(
122 122
             "RESP: [%s] %s\n",
123 123
             resp.status_code,
124 124
             resp.headers)
125 125
         if resp._content_consumed:
126
-            _logger.debug(
126
+            LOG.debug(
127 127
                 "RESP BODY: %s\n",
128 128
                 resp.text)
129 129
 
@@ -176,7 +176,7 @@ class HTTPClient(object):
176 176
         self._http_log_resp(resp)
177 177
 
178 178
         if resp.status_code >= 400:
179
-            _logger.debug(
179
+            LOG.debug(
180 180
                 "Request returned failure status: %s",
181 181
                 resp.status_code)
182 182
             raise exceptions.from_response(resp, method, url)

+ 3
- 3
troveclient/auth_plugin.py View File

@@ -24,7 +24,7 @@ from troveclient._i18n import _
24 24
 from troveclient import exceptions
25 25
 
26 26
 
27
-logger = logging.getLogger(__name__)
27
+LOG = logging.getLogger(__name__)
28 28
 
29 29
 
30 30
 _discovered_plugins = {}
@@ -40,8 +40,8 @@ def discover_auth_systems():
40 40
         try:
41 41
             auth_plugin = ep.load()
42 42
         except (ImportError, pkg_resources.UnknownExtra, AttributeError) as e:
43
-            logger.debug(_("ERROR: Cannot load auth plugin %s") % ep.name)
44
-            logger.debug(e, exc_info=1)
43
+            LOG.debug(_("ERROR: Cannot load auth plugin %s"), ep.name)
44
+            LOG.debug(e, exc_info=1)
45 45
         else:
46 46
             _discovered_plugins[ep.name] = auth_plugin
47 47
 

+ 12
- 12
troveclient/client.py View File

@@ -119,11 +119,11 @@ class HTTPClient(TroveClientMixin):
119 119
         self.auth_system = auth_system
120 120
         self.auth_plugin = auth_plugin
121 121
 
122
-        self._logger = logging.getLogger(__name__)
123
-        if self.http_log_debug and not self._logger.handlers:
122
+        self.LOG = logging.getLogger(__name__)
123
+        if self.http_log_debug and not self.LOG.handlers:
124 124
             ch = logging.StreamHandler()
125
-            self._logger.setLevel(logging.DEBUG)
126
-            self._logger.addHandler(ch)
125
+            self.LOG.setLevel(logging.DEBUG)
126
+            self.LOG.addHandler(ch)
127 127
             if hasattr(requests, 'logging'):
128 128
                 requests.logging.getLogger(requests.__name__).addHandler(ch)
129 129
 
@@ -144,12 +144,12 @@ class HTTPClient(TroveClientMixin):
144 144
 
145 145
         if 'data' in kwargs:
146 146
             string_parts.append(" -d '%s'" % (kwargs['data']))
147
-        self._logger.debug("\nREQ: %s\n" % "".join(string_parts))
147
+        self.LOG.debug("\nREQ: %s\n", "".join(string_parts))
148 148
 
149 149
     def http_log_resp(self, resp):
150 150
         if not self.http_log_debug:
151 151
             return
152
-        self._logger.debug(
152
+        self.LOG.debug(
153 153
             "RESP: [%s] %s\nRESP BODY: %s\n",
154 154
             resp.status_code,
155 155
             resp.headers,
@@ -211,7 +211,7 @@ class HTTPClient(TroveClientMixin):
211 211
             except exceptions.Unauthorized:
212 212
                 if auth_attempts > 0:
213 213
                     raise
214
-                self._logger.debug("Unauthorized, reauthenticating.")
214
+                self.LOG.debug("Unauthorized, reauthenticating.")
215 215
                 self.management_url = self.auth_token = None
216 216
                 # First reauth. Discount this attempt.
217 217
                 attempts -= 1
@@ -226,12 +226,12 @@ class HTTPClient(TroveClientMixin):
226 226
                     raise
227 227
             except requests.exceptions.ConnectionError as e:
228 228
                 # Catch a connection refused from requests.request
229
-                self._logger.debug("Connection refused: %s" % e)
229
+                self.LOG.debug("Connection refused: %s", e)
230 230
                 msg = 'Unable to establish connection: %s' % e
231 231
                 raise exceptions.ConnectionRefused(msg)
232
-            self._logger.debug(
233
-                "Failed attempt(%s of %s), retrying in %s seconds" %
234
-                (attempts, self.retries, backoff))
232
+            self.LOG.debug(
233
+                "Failed attempt(%s of %s), retrying in %s seconds",
234
+                attempts, self.retries, backoff)
235 235
             sleep_lib.sleep(backoff)
236 236
             backoff *= 2
237 237
 
@@ -303,7 +303,7 @@ class HTTPClient(TroveClientMixin):
303 303
         # GET ...:5001/v2.0/tokens/#####/endpoints
304 304
         url = '/'.join([url, 'tokens', '%s?belongsTo=%s'
305 305
                         % (self.proxy_token, self.proxy_tenant_id)])
306
-        self._logger.debug("Using Endpoint URL: %s" % url)
306
+        self.LOG.debug("Using Endpoint URL: %s", url)
307 307
         resp, body = self.request(url, "GET",
308 308
                                   headers={'X-Auth-Token': self.auth_token})
309 309
         return self._extract_service_catalog(url, resp, body,

+ 14
- 14
troveclient/compat/client.py View File

@@ -29,7 +29,7 @@ from troveclient.compat import auth
29 29
 from troveclient.compat import exceptions
30 30
 
31 31
 
32
-_logger = logging.getLogger(__name__)
32
+LOG = logging.getLogger(__name__)
33 33
 RDC_PP = os.environ.get("RDC_PP", "False") == "True"
34 34
 
35 35
 
@@ -39,8 +39,8 @@ expected_errors = (400, 401, 403, 404, 408, 409, 413, 422, 500, 501)
39 39
 def log_to_streamhandler(stream=None):
40 40
     stream = stream or sys.stderr
41 41
     ch = logging.StreamHandler(stream)
42
-    _logger.setLevel(logging.DEBUG)
43
-    _logger.addHandler(ch)
42
+    LOG.setLevel(logging.DEBUG)
43
+    LOG.addHandler(ch)
44 44
 
45 45
 
46 46
 if 'REDDWARFCLIENT_DEBUG' in os.environ and os.environ['REDDWARFCLIENT_DEBUG']:
@@ -105,7 +105,7 @@ class TroveHTTPClient(httplib2.Http):
105 105
             self.pretty_log(args, kwargs, resp, body)
106 106
 
107 107
     def simple_log(self, args, kwargs, resp, body):
108
-        if not _logger.isEnabledFor(logging.DEBUG):
108
+        if not LOG.isEnabledFor(logging.DEBUG):
109 109
             return
110 110
 
111 111
         string_parts = ['curl -i']
@@ -119,13 +119,13 @@ class TroveHTTPClient(httplib2.Http):
119 119
             header = ' -H "%s: %s"' % (element, kwargs['headers'][element])
120 120
             string_parts.append(header)
121 121
 
122
-        _logger.debug("REQ: %s\n" % "".join(string_parts))
122
+        LOG.debug("REQ: %s\n", "".join(string_parts))
123 123
         if 'body' in kwargs:
124
-            _logger.debug("REQ BODY: %s\n" % (kwargs['body']))
125
-        _logger.debug("RESP:%s %s\n", resp, body)
124
+            LOG.debug("REQ BODY: %s\n", kwargs['body'])
125
+        LOG.debug("RESP:%s %s\n", resp, body)
126 126
 
127 127
     def pretty_log(self, args, kwargs, resp, body):
128
-        if not _logger.isEnabledFor(logging.DEBUG):
128
+        if not LOG.isEnabledFor(logging.DEBUG):
129 129
             return
130 130
 
131 131
         string_parts = ['curl -i']
@@ -140,24 +140,24 @@ class TroveHTTPClient(httplib2.Http):
140 140
             string_parts.append(header)
141 141
 
142 142
         curl_cmd = "".join(string_parts)
143
-        _logger.debug("REQUEST:")
143
+        LOG.debug("REQUEST:")
144 144
         if 'body' in kwargs:
145
-            _logger.debug("%s -d '%s'" % (curl_cmd, kwargs['body']))
145
+            LOG.debug("%s -d '%s'", curl_cmd, kwargs['body'])
146 146
             try:
147 147
                 req_body = json.dumps(json.loads(kwargs['body']),
148 148
                                       sort_keys=True, indent=4)
149 149
             except Exception:
150 150
                 req_body = kwargs['body']
151
-            _logger.debug("BODY: %s\n" % (req_body))
151
+            LOG.debug("BODY: %s\n", req_body)
152 152
         else:
153
-            _logger.debug(curl_cmd)
153
+            LOG.debug(curl_cmd)
154 154
 
155 155
         try:
156 156
             resp_body = json.dumps(json.loads(body), sort_keys=True, indent=4)
157 157
         except Exception:
158 158
             resp_body = body
159
-        _logger.debug("RESPONSE HEADERS: %s" % resp)
160
-        _logger.debug("RESPONSE BODY   : %s" % resp_body)
159
+        LOG.debug("RESPONSE HEADERS: %s", resp)
160
+        LOG.debug("RESPONSE BODY   : %s", resp_body)
161 161
 
162 162
     def request(self, *args, **kwargs):
163 163
         kwargs.setdefault('headers', kwargs.get('headers', {}))

+ 2
- 2
troveclient/shell.py View File

@@ -51,7 +51,7 @@ DEFAULT_OS_DATABASE_API_VERSION = "1.0"
51 51
 DEFAULT_TROVE_ENDPOINT_TYPE = 'publicURL'
52 52
 DEFAULT_TROVE_SERVICE_TYPE = 'database'
53 53
 
54
-logger = logging.getLogger(__name__)
54
+LOG = logging.getLogger(__name__)
55 55
 osprofiler_profiler = importutils.try_import("osprofiler.profiler")
56 56
 
57 57
 
@@ -751,7 +751,7 @@ def main():
751 751
         print(_("... terminating trove client"), file=sys.stderr)
752 752
         sys.exit(130)
753 753
     except Exception as e:
754
-        logger.debug(e, exc_info=1)
754
+        LOG.debug(e, exc_info=1)
755 755
         message = six.text_type(e)
756 756
         if not isinstance(message, six.string_types):
757 757
             message = str(message)

Loading…
Cancel
Save