ruff: Enable G (flake8-logging-format) checks

Changes in logic are made due to the following checks.

 G004: Logging statement uses f-string
 G201: Logging .exception(...) should be used instead of
       .error(..., exc_info=True)

Change-Id: I957ef2a9fa49eab6bff748947541e5598de3c98f
Signed-off-by: Takashi Kajinami <kajinamit@oss.nttdata.com>
This commit is contained in:
Takashi Kajinami
2026-07-13 12:12:13 +09:00
parent 7f6bcf1373
commit 6593e47e08
12 changed files with 56 additions and 67 deletions
+2 -3
View File
@@ -165,10 +165,9 @@ class GenericComputePollster(plugin_base.PollsterBase):
'pollster': self.__class__.__name__})
raise plugin_base.PollsterPermanentError(resources)
except Exception as err:
LOG.error(
LOG.exception(
'Could not get %(name)s events for %(id)s: %(e)s', {
'name': self.sample_name, 'id': instance.id, 'e': err},
exc_info=True)
'name': self.sample_name, 'id': instance.id, 'e': err})
class InstanceMetadataPollster(plugin_base.PollsterBase):
+1 -1
View File
@@ -125,7 +125,7 @@ class _Base(plugin_base.PollsterBase):
_Base._ENDPOINT = urlparse.urljoin(rgw_url, '/admin')
except exceptions.EndpointNotFound:
LOG.debug("Radosgw endpoint not found")
LOG.debug(f"Using endpoint {_Base._ENDPOINT} for radosgw connections")
LOG.debug("Using endpoint %s for radosgw connections", _Base._ENDPOINT)
return _Base._ENDPOINT
def _iter_accounts(self, ksclient, cache, tenants):
+1 -2
View File
@@ -122,8 +122,7 @@ class Sink:
try:
self.publishers.append(publisher_manager.get(p))
except Exception:
LOG.error("Unable to load publisher %s", p,
exc_info=True)
LOG.exception("Unable to load publisher %s", p)
self.multi_publish = True if len(self.publishers) > 1 else False
+6 -7
View File
@@ -58,7 +58,7 @@ class EventEndpoint(base.NotificationEndpoint):
except Exception:
if not self.conf.notification.ack_on_event_error:
return oslo_messaging.NotificationResult.REQUEUE
LOG.error('Fail to process a notification', exc_info=True)
LOG.exception('Fail to process a notification')
return oslo_messaging.NotificationResult.HANDLED
@@ -89,12 +89,11 @@ class EventSink(base.Sink):
try:
p.publish_events(events)
except Exception:
LOG.error("Pipeline %(pipeline)s: %(status)s "
"after error from publisher %(pub)s",
{'pipeline': self,
'status': 'Continue' if
self.multi_publish else 'Exit', 'pub': p},
exc_info=True)
LOG.exception("Pipeline %(pipeline)s: %(status)s "
"after error from publisher %(pub)s",
{'pipeline': self,
'status': 'Continue' if
self.multi_publish else 'Exit', 'pub': p})
if not self.multi_publish:
raise
+5 -6
View File
@@ -44,8 +44,8 @@ class SampleEndpoint(base.NotificationEndpoint):
with self.publisher as p:
p(list(self.build_sample(message)))
except Exception:
LOG.error('Fail to process notification message [%s]',
message, exc_info=True)
LOG.exception('Fail to process notification message [%s]',
message)
raise
def build_sample(notification):
@@ -89,10 +89,9 @@ class SampleSink(base.Sink):
try:
p.publish_samples(samples)
except Exception:
LOG.error("Pipeline %(pipeline)s: Continue after "
"error from publisher %(pub)s",
{'pipeline': self, 'pub': p},
exc_info=True)
LOG.exception("Pipeline %(pipeline)s: Continue after "
"error from publisher %(pub)s",
{'pipeline': self, 'pub': p})
@staticmethod
def flush():
+10 -12
View File
@@ -435,10 +435,9 @@ class PollingTask:
source=source_name))
self.resources[key].blacklist.extend(err.fail_res_list)
except Exception as err:
LOG.error(
LOG.exception(
'Continue after error from %(name)s: %(error)s',
{'name': pollster.name, 'error': err},
exc_info=True)
{'name': pollster.name, 'error': err})
def _send_notification(self, samples):
if self.manager.conf.polling.enable_notifications:
@@ -482,8 +481,8 @@ class AgentHeartBeatManager(cotyledon.Service):
raise HeartBeatException("Failed to open socket file "
f"({self._sock_pth}): {err}", conf)
LOG.info("Starting heartbeat child service. Listening"
f" on {self._sock_pth}")
LOG.info("Starting heartbeat child service. Listening on %s",
self._sock_pth)
def _delete_socket(self):
try:
@@ -500,19 +499,18 @@ class AgentHeartBeatManager(cotyledon.Service):
hb = self._queue.get()
with self._lock:
self._status[hb['pollster']] = hb['timestamp']
LOG.debug(f"Updated heartbeat for {hb['pollster']} "
f"({hb['timestamp']})")
LOG.debug("Updated heartbeat for %s %s",
hb['pollster'], hb['timestamp'])
def _send_heartbeat(self):
s, addr = self._sock.accept()
LOG.debug("Heartbeat status report requested "
f"at {self._sock_pth}")
LOG.debug("Heartbeat status report requested at %s", self._sock_pth)
with self._lock:
out = '\n'.join([f"{k} {v}"
for k, v in self._status.items()])
s.sendall(out.encode('utf-8'))
s.close()
LOG.debug(f"Reported heartbeat status:\n{out}")
LOG.debug("Reported heartbeat status:\n%s", out)
def run(self):
super().run()
@@ -634,9 +632,9 @@ class AgentManager(cotyledon.Service):
'pollster': name
}
self._queue.put_nowait(hb)
LOG.debug(f"Polster heartbeat update: {name}")
LOG.debug("Polster heartbeat update: %s", name)
except queue.Full:
LOG.warning(f"Heartbeat queue full. Update failed: {hb}")
LOG.warning("Heartbeat queue full. Update failed: %s", hb)
def create_dynamic_pollsters(self, namespaces):
"""Creates dynamic pollsters
+14 -19
View File
@@ -276,8 +276,7 @@ class GnocchiPublisher(publisher.ConfigPublisherBase):
archive_policy_override,
plugin_manager))
except Exception:
LOG.error("Failed to load resource due to error",
exc_info=True)
LOG.exception("Failed to load resource due to error")
return resource_defs, data.get("archive_policies", [])
def ensures_archives_policies(self):
@@ -443,9 +442,9 @@ class GnocchiPublisher(publisher.ConfigPublisherBase):
"for gnocchi data [%s]: [%s].", measures, gnocchi_data,
str(e))
except Exception as e:
LOG.error("Unexpected exception while pushing measures [%s] for "
"gnocchi data [%s]: [%s].", measures, gnocchi_data,
str(e), exc_info=True)
LOG.exception(
"Unexpected exception while pushing measures [%s] for "
"gnocchi data [%s]: [%s].", measures, gnocchi_data, str(e))
for info in gnocchi_data.values():
resource = info["resource"]
@@ -462,10 +461,10 @@ class GnocchiPublisher(publisher.ConfigPublisherBase):
resource_type, resource.get('id'), resource_extra,
str(e))
except Exception as e:
LOG.error("Unexpected exception updating resource type [%s] "
"with ID [%s] for resource data [%s]: [%s].",
resource_type, resource.get('id'), resource_extra,
str(e), exc_info=True)
LOG.exception(
"Unexpected exception updating resource type [%s] "
"with ID [%s] for resource data [%s]: [%s].",
resource_type, resource.get('id'), resource_extra, str(e))
@staticmethod
def _extract_resources_from_error(e, resource_infos):
@@ -623,18 +622,16 @@ class GnocchiPublisher(publisher.ConfigPublisherBase):
LOG.debug("Create event received on existing resource (%s), "
"ignore it.", resource['id'])
except Exception:
LOG.error("Failed to create resource %s", resource,
exc_info=True)
LOG.exception("Failed to create resource %s", resource)
def _search_resource(self, resource_type, query):
try:
return self._gnocchi.resource.search(
resource_type, json.loads(query))
except Exception:
LOG.error("Fail to search resource type %(resource_type)s "
"with '%(query)s'",
{'resource_type': resource_type, 'query': query},
exc_info=True)
LOG.exception("Fail to search resource type %(resource_type)s "
"with '%(query)s'",
{'resource_type': resource_type, 'query': query})
return []
def _set_update_attributes(self, resource):
@@ -647,8 +644,7 @@ class GnocchiPublisher(publisher.ConfigPublisherBase):
LOG.debug("Update event received on unexisting resource (%s), "
"ignore it.", resource_id)
except Exception:
LOG.error("Fail to update the resource %s", resource,
exc_info=True)
LOG.exception("Fail to update the resource %s", resource)
def _set_ended_at(self, resource, ended_at):
try:
@@ -658,7 +654,6 @@ class GnocchiPublisher(publisher.ConfigPublisherBase):
LOG.debug("Delete event received on unexisting resource (%s), "
"ignore it.", resource['id'])
except Exception:
LOG.error("Fail to update the resource %s", resource,
exc_info=True)
LOG.exception("Fail to update the resource %s", resource)
LOG.debug('Resource %(resource_id)s ended at %(ended_at)s',
{'resource_id': resource["id"], 'ended_at': ended_at})
+2 -2
View File
@@ -166,7 +166,7 @@ class TestEventEndpoint(tests_base.BaseTestCase):
with mock.patch("ceilometer.pipeline.event.LOG") as mock_logger:
ret = self.endpoint.process_notifications('info', [message])
self.assertEqual(oslo_messaging.NotificationResult.REQUEUE, ret)
exception_mock = mock_logger.error
exception_mock = mock_logger.exception
self.assertIn('Exit after error from publisher',
exception_mock.call_args_list[0][0][0] %
exception_mock.call_args_list[0][0][1])
@@ -187,7 +187,7 @@ class TestEventEndpoint(tests_base.BaseTestCase):
with mock.patch("ceilometer.pipeline.event.LOG") as mock_logger:
ret = self.endpoint.process_notifications('info', [message])
self.assertEqual(oslo_messaging.NotificationResult.HANDLED, ret)
exception_mock = mock_logger.error
exception_mock = mock_logger.exception
self.assertIn('Continue after error from publisher',
exception_mock.call_args_list[0][0][0] %
exception_mock.call_args_list[0][0][1])
@@ -55,8 +55,8 @@ class TestHeartBeatManagert(base.BaseTestCase):
group='polling')
manager.AgentHeartBeatManager(0, self.conf, namespaces='compute',
queue=self.queue)
calls = [mock.call("Starting heartbeat child service. Listening"
f" on {self.tmpdir}/ceilometer-compute.socket")]
calls = [mock.call("Starting heartbeat child service. Listening on %s",
f"{self.tmpdir}/ceilometer-compute.socket")]
LOG.info.assert_has_calls(calls)
@mock.patch('ceilometer.polling.manager.LOG')
@@ -70,7 +70,7 @@ class TestHeartBeatManagert(base.BaseTestCase):
self.queue.put_nowait({'timestamp': timestamp, 'pollster': 'test'})
hb._update_status()
calls = [mock.call(f"Updated heartbeat for test ({timestamp})")]
calls = [mock.call("Updated heartbeat for %s %s", "test", timestamp)]
LOG.debug.assert_has_calls(calls)
@mock.patch('ceilometer.polling.manager.LOG')
@@ -100,9 +100,8 @@ class TestHeartBeatManagert(base.BaseTestCase):
# test status report
hb._send_heartbeat()
calls = [mock.call("Heartbeat status report requested "
f"at {self.tmpdir}/ceilometer-central.socket"),
mock.call("Reported heartbeat status:\n"
f"test1 {timestamp}\n"
f"test2 {timestamp}")]
calls = [mock.call("Heartbeat status report requested at %s",
f"{self.tmpdir}/ceilometer-central.socket"),
mock.call("Reported heartbeat status:\n%s",
f"test1 {timestamp}\ntest2 {timestamp}")]
LOG.debug.assert_has_calls(calls)
@@ -677,7 +677,7 @@ class TestPollingAgent(BaseAgent):
'of %(src)s', {'poll': 'test', 'src': 'test_polling'})
])
LOG.debug.assert_has_calls([
mock.call('Polster heartbeat update: test')
mock.call('Polster heartbeat update: %s', 'test')
])
@mock.patch('ceilometer.polling.manager.LOG')
@@ -698,7 +698,7 @@ class TestPollingAgent(BaseAgent):
'of %(src)s', {'poll': 'test', 'src': 'test_polling'})
])
log_mock.debug.assert_has_calls([
mock.call('Polster heartbeat update: test')
mock.call('Polster heartbeat update: %s', 'test')
])
# Even though we enabled 4 threads, we have only one metric configured.
@@ -306,7 +306,7 @@ class PublisherTest(base.BaseTestCase):
url = netutils.urlsplit(
"gnocchi://?resources_definition_file=" + temp)
d = gnocchi.GnocchiPublisher(self.conf.conf, url)
self.assertTrue(mylog.error.called)
self.assertTrue(mylog.exception.called)
self.assertEqual(0, len(d.resources_definition))
@mock.patch('ceilometer.publisher.gnocchi.GnocchiPublisher'
@@ -886,15 +886,15 @@ class PublisherWorkflowTest(base.BaseTestCase,
or (self.update_resource_fail and update_attributes)):
if self.update_resource_fail and update_attributes:
logger.error.assert_called_with(
logger.exception.assert_called_with(
'Unexpected exception updating resource type [%s] with '
'ID [%s] for resource data [%s]: [%s].', resource_type,
resource_id, mock.ANY, 'boom!', exc_info=True)
resource_id, mock.ANY, 'boom!')
else:
logger.error.assert_called_with(
logger.exception.assert_called_with(
'Unexpected exception while pushing measures [%s] for '
'gnocchi data [%s]: [%s].', expected_measures_in_log,
mock.ANY, 'boom!', exc_info=True)
mock.ANY, 'boom!')
else:
self.assertEqual(0, logger.error.call_count)
self.assertEqual(expected_calls, fakeclient.mock_calls)
+1
View File
@@ -28,6 +28,7 @@ select = [
"E9",
# pyflakes
"F",
"G",
"LOG",
"UP",
"W",