Skip to content

Commit ba8ad5e

Browse files
committed
Add a hacking rule for string interpolation at logging
String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. See the oslo i18n guideline * https://docs.openstack.org/oslo.i18n/latest/user/guidelines.html#adding-variables-to-log-messages and * https://github.com/openstack-dev/hacking/blob/master/hacking/checks/other.py#L39 Change-Id: I8a4f5f896865aebbff88ee894f0081e58cfce9ef
1 parent 465d3c0 commit ba8ad5e

27 files changed

+75
-73
lines changed

HACKING.rst

+1
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@ Magnum Specific Commandments
2121
- [M339] Don't use xrange()
2222
- [M340] Check for explicit import of the _ function.
2323
- [M352] LOG.warn is deprecated. Enforce use of LOG.warning.
24+
- [M353] String interpolation should be delayed at logging calls.

magnum/api/app.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def load_app():
5959

6060
if not cfg_file:
6161
raise cfg.ConfigFilesNotFoundError([CONF.api.api_paste_config])
62-
LOG.info("Full WSGI config used: %s" % cfg_file)
62+
LOG.info("Full WSGI config used: %s", cfg_file)
6363
return deploy.loadapp("config:" + cfg_file)
6464

6565

magnum/api/controllers/v1/bay.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ def _collect_fault_info(self, context, bay):
361361
failed_resources = []
362362
LOG.warning("Failed to retrieve failed resources for "
363363
"bay %(bay)s from Heat stack %(stack)s "
364-
"due to error: %(e)s" %
364+
"due to error: %(e)s",
365365
{'bay': bay.uuid, 'stack': bay.stack_id, 'e': e},
366366
exc_info=True)
367367

magnum/api/controllers/v1/cluster.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -334,7 +334,7 @@ def _collect_fault_info(self, context, cluster):
334334
failed_resources = []
335335
LOG.warning("Failed to retrieve failed resources for "
336336
"cluster %(cluster)s from Heat stack "
337-
"%(stack)s due to error: %(e)s" %
337+
"%(stack)s due to error: %(e)s",
338338
{'cluster': cluster.uuid,
339339
'stack': cluster.stack_id, 'e': e},
340340
exc_info=True)

magnum/cmd/api.py

100644100755
+3-3
Original file line numberDiff line numberDiff line change
@@ -72,17 +72,17 @@ def main():
7272
# Create the WSGI server and start it
7373
host, port = CONF.api.host, CONF.api.port
7474

75-
LOG.info('Starting server in PID %s' % os.getpid())
75+
LOG.info('Starting server in PID %s', os.getpid())
7676
LOG.debug("Configuration:")
7777
CONF.log_opt_values(LOG, logging.DEBUG)
7878

79-
LOG.info('Serving on %(proto)s://%(host)s:%(port)s' %
79+
LOG.info('Serving on %(proto)s://%(host)s:%(port)s',
8080
dict(proto="https" if use_ssl else "http", host=host, port=port))
8181

8282
workers = CONF.api.workers
8383
if not workers:
8484
workers = processutils.get_worker_count()
8585
LOG.info('Server will handle each request in a new process up to'
86-
' %s concurrent processes' % workers)
86+
' %s concurrent processes', workers)
8787
serving.run_simple(host, port, app, processes=workers,
8888
ssl_context=_get_ssl_configs(use_ssl))

magnum/cmd/conductor.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def main():
4141

4242
gmr.TextGuruMeditation.setup_autorun(version)
4343

44-
LOG.info('Starting server in PID %s' % os.getpid())
44+
LOG.info('Starting server in PID %s', os.getpid())
4545
LOG.debug("Configuration:")
4646
CONF.log_opt_values(LOG, logging.DEBUG)
4747

magnum/common/exception.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ def __init__(self, message=None, **kwargs):
9292
# kwargs doesn't match a variable in the message
9393
# log the issue and the kwargs
9494
LOG.exception('Exception in string format operation, '
95-
'kwargs: %s' % kwargs)
95+
'kwargs: %s', kwargs)
9696
try:
9797
if CONF.fatal_exception_format_errors:
9898
raise

magnum/common/keystone.py

100644100755
+2-2
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ def _get_legacy_auth(self):
102102
LOG.warning('Auth plugin and its options for service user '
103103
'must be provided in [%(new)s] section. '
104104
'Using values from [%(old)s] section is '
105-
'deprecated.' % {'new': ksconf.CFG_GROUP,
106-
'old': ksconf.CFG_LEGACY_GROUP})
105+
'deprecated.', {'new': ksconf.CFG_GROUP,
106+
'old': ksconf.CFG_LEGACY_GROUP})
107107

108108
conf = getattr(CONF, ksconf.CFG_LEGACY_GROUP)
109109

magnum/common/urlfetch.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ def get(url, allowed_schemes=('http', 'https')):
3838
the allowed_schemes argument.
3939
Raise an IOError if getting the data fails.
4040
"""
41-
LOG.info('Fetching data from %s' % url)
41+
LOG.info('Fetching data from %s', url)
4242

4343
components = urllib.parse.urlparse(url)
4444

magnum/common/utils.py

100644100755
+6-6
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,10 @@ def execute(*cmd, **kwargs):
8585
if kwargs.get('run_as_root') and 'root_helper' not in kwargs:
8686
kwargs['root_helper'] = _get_root_helper()
8787
result = processutils.execute(*cmd, **kwargs)
88-
LOG.debug('Execution completed, command line is "%s"' %
88+
LOG.debug('Execution completed, command line is "%s"',
8989
' '.join(map(str, cmd)))
90-
LOG.debug('Command stdout is: "%s"' % result[0])
91-
LOG.debug('Command stderr is: "%s"' % result[1])
90+
LOG.debug('Command stdout is: "%s"', result[0])
91+
LOG.debug('Command stderr is: "%s"', result[1])
9292
return result
9393

9494

@@ -125,15 +125,15 @@ def tempdir(**kwargs):
125125
try:
126126
shutil.rmtree(tmpdir)
127127
except OSError as e:
128-
LOG.error('Could not remove tmpdir: %s' % e)
128+
LOG.error('Could not remove tmpdir: %s', e)
129129

130130

131131
def rmtree_without_raise(path):
132132
try:
133133
if os.path.isdir(path):
134134
shutil.rmtree(path)
135135
except OSError as e:
136-
LOG.warning("Failed to remove dir %(path)s, error: %(e)s" %
136+
LOG.warning("Failed to remove dir %(path)s, error: %(e)s",
137137
{'path': path, 'e': e})
138138

139139

@@ -148,7 +148,7 @@ def safe_rstrip(value, chars=None):
148148
if not isinstance(value, six.string_types):
149149
LOG.warning("Failed to remove trailing character. "
150150
"Returning original object. "
151-
"Supplied object is not a string: %s," % value)
151+
"Supplied object is not a string: %s,", value)
152152
return value
153153

154154
return value.rstrip(chars) or value

magnum/conductor/handlers/cluster_conductor.py

100644100755
+2-2
Original file line numberDiff line numberDiff line change
@@ -151,14 +151,14 @@ def cluster_delete(self, context, uuid):
151151
cluster.status_reason = None
152152
except exc.HTTPNotFound:
153153
LOG.info('The cluster %s was not found during cluster'
154-
' deletion.' % cluster.id)
154+
' deletion.', cluster.id)
155155
try:
156156
trust_manager.delete_trustee_and_trust(osc, context, cluster)
157157
cert_manager.delete_certificates_from_cluster(cluster,
158158
context=context)
159159
cluster.destroy()
160160
except exception.ClusterNotFound:
161-
LOG.info('The cluster %s has been deleted by others.' %
161+
LOG.info('The cluster %s has been deleted by others.',
162162
uuid)
163163
conductor_utils.notify_about_cluster_operation(
164164
context, taxonomy.ACTION_DELETE, taxonomy.OUTCOME_SUCCESS)

magnum/conductor/handlers/common/cert_manager.py

100644100755
+5-5
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def _generate_ca_cert(issuer_name, context=None):
4343
name=issuer_name,
4444
context=context,
4545
)
46-
LOG.debug('CA cert is created: %s' % ca_cert_ref)
46+
LOG.debug('CA cert is created: %s', ca_cert_ref)
4747
return ca_cert_ref, ca_cert, ca_password
4848

4949

@@ -70,7 +70,7 @@ def _generate_client_cert(issuer_name, ca_cert, ca_password, context=None):
7070
name=CONDUCTOR_CLIENT_NAME,
7171
context=context
7272
)
73-
LOG.debug('Magnum client cert is created: %s' % magnum_cert_ref)
73+
LOG.debug('Magnum client cert is created: %s', magnum_cert_ref)
7474
return magnum_cert_ref
7575

7676

@@ -92,7 +92,7 @@ def generate_certificates_to_cluster(cluster, context=None):
9292
try:
9393
issuer_name = _get_issuer_name(cluster)
9494

95-
LOG.debug('Start to generate certificates: %s' % issuer_name)
95+
LOG.debug('Start to generate certificates: %s', issuer_name)
9696

9797
ca_cert_ref, ca_cert, ca_password = _generate_ca_cert(issuer_name,
9898
context=context)
@@ -104,7 +104,7 @@ def generate_certificates_to_cluster(cluster, context=None):
104104
cluster.ca_cert_ref = ca_cert_ref
105105
cluster.magnum_cert_ref = magnum_cert_ref
106106
except Exception:
107-
LOG.exception('Failed to generate certificates for Cluster: %s' %
107+
LOG.exception('Failed to generate certificates for Cluster: %s',
108108
cluster.uuid)
109109
raise exception.CertificatesToClusterFailed(cluster_uuid=cluster.uuid)
110110

@@ -174,5 +174,5 @@ def delete_certificates_from_cluster(cluster, context=None):
174174
cert_manager.get_backend().CertManager.delete_cert(
175175
cert_ref, resource_ref=cluster.uuid, context=context)
176176
except Exception:
177-
LOG.warning("Deleting certs is failed for Cluster %s" %
177+
LOG.warning("Deleting certs is failed for Cluster %s",
178178
cluster.uuid)

magnum/conductor/handlers/common/trust_manager.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def create_trustee_and_trust(osc, cluster):
3737

3838
except Exception:
3939
LOG.exception(
40-
'Failed to create trustee and trust for Cluster: %s' %
40+
'Failed to create trustee and trust for Cluster: %s',
4141
cluster.uuid)
4242
raise exception.TrusteeOrTrustToClusterFailed(
4343
cluster_uuid=cluster.uuid)

magnum/conductor/k8s_api.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def _create_temp_file_with_content(self, content):
3737
tmp.write(content)
3838
tmp.flush()
3939
except Exception as err:
40-
LOG.error("Error while creating temp file: %s" % err)
40+
LOG.error("Error while creating temp file: %s", err)
4141
raise
4242
return tmp
4343

magnum/conductor/scale_manager.py

100644100755
+2-2
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,13 @@ def get_removal_nodes(self, hosts_output):
6767
LOG.warning(
6868
"About to remove %(num_removal)d nodes, which is larger than "
6969
"the number of empty nodes (%(num_empty)d). %(num_non_empty)d "
70-
"non-empty nodes will be removed." % {
70+
"non-empty nodes will be removed.", {
7171
'num_removal': num_of_removal,
7272
'num_empty': len(hosts_no_container),
7373
'num_non_empty': num_of_removal - len(hosts_no_container)})
7474

7575
hosts_to_remove = hosts_no_container[0:num_of_removal]
76-
LOG.info('Require removal of hosts: %s' % hosts_to_remove)
76+
LOG.info('Require removal of hosts: %s', hosts_to_remove)
7777

7878
return hosts_to_remove
7979

magnum/drivers/heat/driver.py

100644100755
+6-6
Original file line numberDiff line numberDiff line change
@@ -190,17 +190,17 @@ def poll_and_check(self):
190190
self._cluster_failed(stack)
191191

192192
def _delete_complete(self):
193-
LOG.info('Cluster has been deleted, stack_id: %s'
194-
% self.cluster.stack_id)
193+
LOG.info('Cluster has been deleted, stack_id: %s',
194+
self.cluster.stack_id)
195195
try:
196196
trust_manager.delete_trustee_and_trust(self.openstack_client,
197197
self.context,
198198
self.cluster)
199199
cert_manager.delete_certificates_from_cluster(self.cluster,
200200
context=self.context)
201201
except exception.ClusterNotFound:
202-
LOG.info('The cluster %s has been deleted by others.'
203-
% self.cluster.uuid)
202+
LOG.info('The cluster %s has been deleted by others.',
203+
self.cluster.uuid)
204204

205205
def _sync_cluster_status(self, stack):
206206
self.cluster.status = stack.stack_status
@@ -233,7 +233,7 @@ def _sync_cluster_and_template_status(self, stack):
233233
def _cluster_failed(self, stack):
234234
LOG.error('Cluster error, stack status: %(cluster_status)s, '
235235
'stack_id: %(stack_id)s, '
236-
'reason: %(reason)s' %
236+
'reason: %(reason)s',
237237
{'cluster_status': stack.stack_status,
238238
'stack_id': self.cluster.stack_id,
239239
'reason': self.cluster.status_reason})
@@ -253,6 +253,6 @@ def _sync_missing_stack(self, new_status):
253253
self.cluster.save()
254254
LOG.info("Cluster with id %(id)s has been set to "
255255
"%(status)s due to stack with id %(sid)s "
256-
"not found in Heat." %
256+
"not found in Heat.",
257257
{'id': self.cluster.id, 'status': self.cluster.status,
258258
'sid': self.cluster.stack_id})

magnum/drivers/heat/template_def.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def get_output_value(self, stack):
100100
if output['output_key'] == self.heat_output:
101101
return output['output_value']
102102

103-
LOG.warning('stack does not have output_key %s' % self.heat_output)
103+
LOG.warning('stack does not have output_key %s', self.heat_output)
104104
return None
105105

106106

magnum/drivers/swarm_fedora_atomic_v1/monitor.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def pull_data(self):
5151
container = docker.inspect_container(container['Id'])
5252
except Exception as e:
5353
LOG.warning("Ignore error [%(e)s] when inspecting "
54-
"container %(container_id)s." %
54+
"container %(container_id)s.",
5555
{'e': e, 'container_id': container['Id']},
5656
exc_info=True)
5757
containers.append(container)

magnum/service/periodic.py

100644100755
+3-3
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def sync_cluster_status(self, ctx):
135135

136136
except Exception as e:
137137
LOG.warning(
138-
"Ignore error [%s] when syncing up cluster status." %
138+
"Ignore error [%s] when syncing up cluster status.",
139139
e, exc_info=True)
140140

141141
@periodic_task.periodic_task(run_immediately=True)
@@ -157,7 +157,7 @@ def _send_cluster_metrics(self, ctx):
157157
except Exception as e:
158158
LOG.warning(
159159
"Skip pulling data from cluster %(cluster)s due to "
160-
"error: %(e)s" %
160+
"error: %(e)s",
161161
{'e': e, 'cluster': cluster.uuid}, exc_info=True)
162162
continue
163163

@@ -172,7 +172,7 @@ def _send_cluster_metrics(self, ctx):
172172
metrics.append(metric)
173173
except Exception as e:
174174
LOG.warning("Skip adding metric %(name)s due to "
175-
"error: %(e)s" %
175+
"error: %(e)s",
176176
{'e': e, 'name': name}, exc_info=True)
177177

178178
message = dict(metrics=metrics,

magnum/tests/functional/api/base.py

100644100755
+1-1
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def get_credentials_with_keypair(cls, name=None,
106106
except Exception:
107107
keypair_body = keypairs_client.create_keypair(
108108
name=config.Config.keypair_id)
109-
cls.LOG.debug("Keypair body: %s" % keypair_body)
109+
cls.LOG.debug("Keypair body: %s", keypair_body)
110110
keypair = keypair_body['keypair']['private_key']
111111
return (creds, keypair)
112112

magnum/tests/functional/api/v1/clients/bay_client.py

100644100755
+8-8
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ def wait_for_created_bay(self, bay_id, delete_on_error=True):
120120
lambda: self.does_bay_exist(bay_id), 10, 1800)
121121
except Exception:
122122
# In error state. Clean up the bay id if desired
123-
self.LOG.error('Bay %s entered an exception state.' % bay_id)
123+
self.LOG.error('Bay %s entered an exception state.', bay_id)
124124
if delete_on_error:
125125
self.LOG.error('We will attempt to delete bays now.')
126126
self.delete_bay(bay_id)
@@ -136,35 +136,35 @@ def is_bay_in_final_state(self, bay_id):
136136
resp, model = self.get_bay(bay_id)
137137
if model.status in ['CREATED', 'CREATE_COMPLETE',
138138
'ERROR', 'CREATE_FAILED']:
139-
self.LOG.info('Bay %s succeeded.' % bay_id)
139+
self.LOG.info('Bay %s succeeded.', bay_id)
140140
return True
141141
else:
142142
return False
143143
except exceptions.NotFound:
144-
self.LOG.warning('Bay %s is not found.' % bay_id)
144+
self.LOG.warning('Bay %s is not found.', bay_id)
145145
return False
146146

147147
def does_bay_exist(self, bay_id):
148148
try:
149149
resp, model = self.get_bay(bay_id)
150150
if model.status in ['CREATED', 'CREATE_COMPLETE']:
151-
self.LOG.info('Bay %s is created.' % bay_id)
151+
self.LOG.info('Bay %s is created.', bay_id)
152152
return True
153153
elif model.status in ['ERROR', 'CREATE_FAILED']:
154-
self.LOG.error('Bay %s is in fail state.' % bay_id)
154+
self.LOG.error('Bay %s is in fail state.', bay_id)
155155
raise exceptions.ServerFault(
156-
"Got into an error condition: %s for %s" %
156+
"Got into an error condition: %s for %s",
157157
(model.status, bay_id))
158158
else:
159159
return False
160160
except exceptions.NotFound:
161-
self.LOG.warning('Bay %s is not found.' % bay_id)
161+
self.LOG.warning('Bay %s is not found.', bay_id)
162162
return False
163163

164164
def does_bay_not_exist(self, bay_id):
165165
try:
166166
self.get_bay(bay_id)
167167
except exceptions.NotFound:
168-
self.LOG.warning('Bay %s is not found.' % bay_id)
168+
self.LOG.warning('Bay %s is not found.', bay_id)
169169
return True
170170
return False

0 commit comments

Comments
 (0)