diff --git a/HACKING.rst b/HACKING.rst index e7277952..043115c4 100644 --- a/HACKING.rst +++ b/HACKING.rst @@ -26,9 +26,6 @@ Masakari Specific Commandments - [M309] Don't import translation in tests - [M310] Setting CONF.* attributes directly in tests is forbidden. Use self.flags(option=value) instead. -- [M311] Validate that LOG.info messages use _LI. -- [M312] Validate that LOG.exception messages use _LE. -- [M313] Validate that LOG.warning and LOG.warn messages use _LW. - [M314] Log messages require translations! - [M315] Method's default argument shouldn't be mutable - [M316] Ensure that the _() function is explicitly imported to ensure proper translations. diff --git a/masakari/api/openstack/__init__.py b/masakari/api/openstack/__init__.py index b856bd10..658cdd99 100644 --- a/masakari/api/openstack/__init__.py +++ b/masakari/api/openstack/__init__.py @@ -25,7 +25,6 @@ import webob.exc from masakari.api.openstack import wsgi import masakari.conf -from masakari.i18n import _LE, _LI, _LW from masakari.i18n import translate from masakari import utils from masakari import wsgi as base_wsgi @@ -49,7 +48,7 @@ class FaultWrapper(base_wsgi.Middleware): status, webob.exc.HTTPInternalServerError)() def _error(self, inner, req): - LOG.exception(_LE("Caught error: %s"), six.text_type(inner)) + LOG.exception("Caught error: %s", six.text_type(inner)) safe = getattr(inner, 'safe', False) headers = getattr(inner, 'headers', None) @@ -58,7 +57,7 @@ class FaultWrapper(base_wsgi.Middleware): status = 500 msg_dict = dict(url=req.url, status=status) - LOG.info(_LI("%(url)s returned with HTTP %(status)d"), msg_dict) + LOG.info("%(url)s returned with HTTP %(status)d", msg_dict) outer = self.status_to_type(status) if headers: outer.headers = headers @@ -181,7 +180,7 @@ class APIRouterV1(base_wsgi.Router): self._register_resources_check_inherits(mapper) self.api_extension_manager.map(self._register_controllers) - LOG.info(_LI("Loaded extensions: %s"), + LOG.info("Loaded extensions: %s", sorted(self.loaded_extension_info.get_extensions().keys())) super(APIRouterV1, self).__init__(mapper) @@ -269,8 +268,8 @@ class APIRouterV1(base_wsgi.Router): controller = extension.controller if collection not in self.resources: - LOG.warning(_LW('Extension %(ext_name)s: Cannot extend ' - 'resource %(collection)s: No such resource'), + LOG.warning('Extension %(ext_name)s: Cannot extend ' + 'resource %(collection)s: No such resource', {'ext_name': ext_name, 'collection': collection}) continue diff --git a/masakari/api/openstack/extensions.py b/masakari/api/openstack/extensions.py index 782905c0..3b68b1b7 100644 --- a/masakari/api/openstack/extensions.py +++ b/masakari/api/openstack/extensions.py @@ -25,7 +25,7 @@ import webob.exc import masakari.api.openstack from masakari.api.openstack import wsgi from masakari import exception -from masakari.i18n import _, _LE, _LW +from masakari.i18n import _ import masakari.policy LOG = logging.getLogger(__name__) @@ -176,7 +176,7 @@ class ExtensionManager(object): try: extension.is_valid() except AttributeError: - LOG.exception(_LE("Exception loading extension")) + LOG.exception("Exception loading extension") return False return True @@ -211,8 +211,8 @@ class ExtensionManager(object): try: self.load_extension(ext_factory) except Exception as exc: - LOG.warning(_LW('Failed to load extension %(ext_factory)s: ' - '%(exc)s'), + LOG.warning('Failed to load extension %(ext_factory)s: ' + '%(exc)s', {'ext_factory': ext_factory, 'exc': exc}) @@ -282,8 +282,7 @@ def load_standard_extensions(ext_mgr, logger, path, package, ext_list=None): try: ext_mgr.load_extension(classpath) except Exception as exc: - logger.warn(_LW('Failed to load extension %(classpath)s: ' - '%(exc)s'), + logger.warn('Failed to load extension %(classpath)s: %(exc)s', {'classpath': classpath, 'exc': exc}) # Now, let's consider any subdirectories we may have... @@ -305,8 +304,8 @@ def load_standard_extensions(ext_mgr, logger, path, package, ext_list=None): try: ext(ext_mgr) except Exception as exc: - logger.warn(_LW('Failed to load extension %(ext_name)s:' - '%(exc)s'), + logger.warn('Failed to load extension %(ext_name)s:' + '%(exc)s', {'ext_name': ext_name, 'exc': exc}) # Update the list of directories we'll explore... @@ -441,7 +440,7 @@ def expected_errors(errors): raise elif isinstance(exc, exception.ValidationError): raise - LOG.exception(_LE("Unexpected exception in API method")) + LOG.exception("Unexpected exception in API method") msg = _('Unexpected API Error. Please report this at ' 'http://bugs.launchpad.net/masakari/ and attach the ' 'Masakari API log if possible.\n%s') % type(exc) diff --git a/masakari/api/openstack/ha/extension_info.py b/masakari/api/openstack/ha/extension_info.py index 31b0d1a0..c870ce7a 100644 --- a/masakari/api/openstack/ha/extension_info.py +++ b/masakari/api/openstack/ha/extension_info.py @@ -19,7 +19,6 @@ import webob.exc from masakari.api.openstack import extensions from masakari.api.openstack import wsgi from masakari import exception -from masakari.i18n import _LE ALIAS = 'extensions' LOG = logging.getLogger(__name__) @@ -131,7 +130,7 @@ class LoadedExtensionInfo(object): try: extension.is_valid() except AttributeError: - LOG.exception(_LE("Exception loading extension")) + LOG.exception("Exception loading extension") return False return True diff --git a/masakari/api/openstack/wsgi.py b/masakari/api/openstack/wsgi.py index fbf55954..fb4648b0 100644 --- a/masakari/api/openstack/wsgi.py +++ b/masakari/api/openstack/wsgi.py @@ -28,7 +28,7 @@ from masakari.api import api_version_request as api_version from masakari.api import versioned_method from masakari import exception from masakari import i18n -from masakari.i18n import _, _LE, _LI +from masakari.i18n import _ from masakari import utils from masakari import wsgi @@ -378,14 +378,14 @@ class ResourceExceptionHandler(object): explanation=ex_value.format_message())) elif isinstance(ex_value, TypeError): exc_info = (ex_type, ex_value, ex_traceback) - LOG.error(_LE('Exception handling resource: %s'), ex_value, + LOG.error('Exception handling resource: %s', ex_value, exc_info=exc_info) raise Fault(webob.exc.HTTPBadRequest()) elif isinstance(ex_value, Fault): - LOG.info(_LI("Fault thrown: %s"), ex_value) + LOG.info("Fault thrown: %s", ex_value) raise ex_value elif isinstance(ex_value, webob.exc.HTTPException): - LOG.info(_LI("HTTP exception thrown: %s"), ex_value) + LOG.info("HTTP exception thrown: %s", ex_value) raise Fault(ex_value) # We didn't handle the exception diff --git a/masakari/cmd/api.py b/masakari/cmd/api.py index 1cd59c45..4f8ac251 100644 --- a/masakari/cmd/api.py +++ b/masakari/cmd/api.py @@ -25,7 +25,6 @@ import six import masakari.conf from masakari import config from masakari import exception -from masakari.i18n import _LE, _LW from masakari import objects from masakari import service @@ -46,13 +45,12 @@ def main(): launcher.launch_service(server, workers=server.workers or 1) started += 1 except exception.PasteAppNotFound as ex: - log.warning( - _LW("%s. ``enabled_apis`` includes bad values. " - "Fix to remove this warning."), six.text_type(ex)) + log.warning("%s. ``enabled_apis`` includes bad values. " + "Fix to remove this warning.", six.text_type(ex)) if started == 0: - log.error(_LE('No APIs were started. ' - 'Check the enabled_apis config option.')) + log.error('No APIs were started. ' + 'Check the enabled_apis config option.') sys.exit(1) launcher.wait() diff --git a/masakari/compute/nova.py b/masakari/compute/nova.py index 9f4b926b..da9a6455 100644 --- a/masakari/compute/nova.py +++ b/masakari/compute/nova.py @@ -33,7 +33,6 @@ import six from masakari import conf from masakari import context as ctx from masakari import exception -from masakari.i18n import _LI CONF = conf.CONF CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token') @@ -136,7 +135,7 @@ class API(object): 'all_tenants': True } nova = novaclient(context) - LOG.info(_LI('Fetch Server list on %s'), host) + LOG.info('Fetch Server list on %s', host) return nova.servers.list(detailed=True, search_opts=opts) @translate_nova_exception @@ -146,14 +145,14 @@ class API(object): nova = novaclient(context) if not enable: - LOG.info(_LI('Disable nova-compute on %s'), host_name) + LOG.info('Disable nova-compute on %s', host_name) if reason: nova.services.disable_log_reason(host_name, 'nova-compute', reason) else: nova.services.disable(host_name, 'nova-compute') else: - LOG.info(_LI('Enable nova-compute on %s'), host_name) + LOG.info('Enable nova-compute on %s', host_name) nova.services.enable(host_name, 'nova-compute') @translate_nova_exception @@ -167,8 +166,8 @@ class API(object): def evacuate_instance(self, context, uuid, target=None, on_shared_storage=True): """Evacuate an instance from failed host to specified host.""" - msg = (_LI('Call evacuate command for instance %(uuid)s on host ' - '%(target)s')) + msg = ('Call evacuate command for instance %(uuid)s on host ' + '%(target)s') LOG.info(msg, {'uuid': uuid, 'target': target}) nova = novaclient(context) nova.servers.evacuate(uuid, host=target, @@ -177,8 +176,8 @@ class API(object): @translate_nova_exception def reset_instance_state(self, context, uuid, status='error'): """Reset the state of an instance to active or error.""" - msg = (_LI('Call reset state command on instance %(uuid)s to ' - 'status: %(status)s.')) + msg = ('Call reset state command on instance %(uuid)s to ' + 'status: %(status)s.') LOG.info(msg, {'uuid': uuid, 'status': status}) nova = novaclient(context) nova.servers.reset_state(uuid, status) @@ -187,7 +186,7 @@ class API(object): def get_server(self, context, uuid): """Get a server.""" nova = novaclient(context) - msg = (_LI('Call get server command for instance %(uuid)s')) + msg = ('Call get server command for instance %(uuid)s') LOG.info(msg, {'uuid': uuid}) return nova.servers.get(uuid) @@ -195,7 +194,7 @@ class API(object): def stop_server(self, context, uuid): """Stop a server.""" nova = novaclient(context) - msg = (_LI('Call stop server command for instance %(uuid)s')) + msg = ('Call stop server command for instance %(uuid)s') LOG.info(msg, {'uuid': uuid}) return nova.servers.stop(uuid) @@ -203,7 +202,7 @@ class API(object): def start_server(self, context, uuid): """Start a server.""" nova = novaclient(context) - msg = (_LI('Call start server command for instance %(uuid)s')) + msg = ('Call start server command for instance %(uuid)s') LOG.info(msg, {'uuid': uuid}) return nova.servers.start(uuid) @@ -211,15 +210,14 @@ class API(object): def get_aggregate_list(self, context): """Get all aggregate list.""" nova = novaclient(context) - LOG.info(_LI('Call aggregate-list command to get list of all ' - 'aggregates.')) + LOG.info('Call aggregate-list command to get list of all aggregates.') return nova.aggregates.list() @translate_nova_exception def add_host_to_aggregate(self, context, host, aggregate): """Add host to given aggregate.""" nova = novaclient(context) - msg = _LI("Call add_host command to add host '%(host_name)s' to " - "aggregate '%(aggregate_name)s'.") + msg = ("Call add_host command to add host '%(host_name)s' to " + "aggregate '%(aggregate_name)s'.") LOG.info(msg, {'host_name': host, 'aggregate_name': aggregate.name}) return nova.aggregates.add_host(aggregate.id, host) diff --git a/masakari/engine/driver.py b/masakari/engine/driver.py index 2806b9d7..5b116fc2 100644 --- a/masakari/engine/driver.py +++ b/masakari/engine/driver.py @@ -28,7 +28,6 @@ import six from stevedore import driver import masakari.conf -from masakari.i18n import _LE, _LI from masakari import utils @@ -68,17 +67,16 @@ def load_masakari_driver(masakari_driver=None): masakari_driver = CONF.notification_driver if not masakari_driver: - LOG.error(_LE("Notification driver option required, but not" - "specified")) + LOG.error("Notification driver option required, but not specified") sys.exit(1) - LOG.info(_LI("Loading masakari notification driver '%s'"), masakari_driver) + LOG.info("Loading masakari notification driver '%s'", masakari_driver) try: notification_driver = driver.DriverManager('masakari.driver', masakari_driver, invoke_on_load=True).driver return utils.check_isinstance(notification_driver, NotificationDriver) except ImportError: - LOG.exception(_LE("Failed to load notification driver " - "'%s'."), masakari_driver) + LOG.exception("Failed to load notification driver '%s'.", + masakari_driver) sys.exit(1) diff --git a/masakari/engine/drivers/taskflow/driver.py b/masakari/engine/drivers/taskflow/driver.py index 84889686..e78db165 100644 --- a/masakari/engine/drivers/taskflow/driver.py +++ b/masakari/engine/drivers/taskflow/driver.py @@ -29,7 +29,7 @@ from masakari.engine.drivers.taskflow import host_failure from masakari.engine.drivers.taskflow import instance_failure from masakari.engine.drivers.taskflow import process_failure from masakari import exception -from masakari.i18n import _, _LW +from masakari.i18n import _ from masakari.objects import fields @@ -77,10 +77,10 @@ class TaskFlowDriver(driver.NotificationDriver): # Caught generic Exception to make sure that any failure # should lead to execute 'reserved_host' recovery workflow. - msg = _LW("Failed to evacuate all instances from " - "failed_host: '%(failed_host)s' using " - "'%(auto)s' workflow, retrying using " - "'%(reserved_host)s' workflow.") + msg = ("Failed to evacuate all instances from " + "failed_host: '%(failed_host)s' using " + "'%(auto)s' workflow, retrying using " + "'%(reserved_host)s' workflow.") LOG.warning(msg, { 'failed_host': process_what['host_name'], 'auto': fields.FailoverSegmentRecoveryMethod.AUTO, @@ -103,10 +103,10 @@ class TaskFlowDriver(driver.NotificationDriver): # Caught generic Exception to make sure that any failure # should lead to execute 'auto' recovery workflow. - msg = _LW("Failed to evacuate all instances from " - "failed_host '%(failed_host)s' using " - "'%(reserved_host)s' workflow, retrying using " - "'%(auto)s' workflow") + msg = ("Failed to evacuate all instances from " + "failed_host '%(failed_host)s' using " + "'%(reserved_host)s' workflow, retrying using " + "'%(auto)s' workflow") LOG.warning(msg, { 'failed_host': process_what['host_name'], 'reserved_host': @@ -189,7 +189,7 @@ class TaskFlowDriver(driver.NotificationDriver): if process_name == "nova-compute": recovery_flow = process_failure.get_compute_process_recovery_flow else: - LOG.warning(_LW("Skipping recovery for process: %s."), + LOG.warning("Skipping recovery for process: %s.", process_name) raise exception.SkipProcessRecoveryException() diff --git a/masakari/engine/drivers/taskflow/host_failure.py b/masakari/engine/drivers/taskflow/host_failure.py index bbea55f1..541eac0b 100644 --- a/masakari/engine/drivers/taskflow/host_failure.py +++ b/masakari/engine/drivers/taskflow/host_failure.py @@ -26,7 +26,7 @@ from taskflow import retry import masakari.conf from masakari.engine.drivers.taskflow import base from masakari import exception -from masakari.i18n import _, _LI +from masakari.i18n import _ from masakari import utils @@ -48,8 +48,8 @@ class DisableComputeServiceTask(base.MasakariTask): self.novaclient.enable_disable_service(context, host_name) # Sleep until nova-compute service is marked as disabled. - msg = _LI("Sleeping %(wait)s sec before starting recovery " - "thread until nova recognizes the node down.") + msg = ("Sleeping %(wait)s sec before starting recovery " + "thread until nova recognizes the node down.") LOG.info(msg, {'wait': CONF.wait_period_after_service_update}) eventlet.sleep(CONF.wait_period_after_service_update) @@ -118,8 +118,8 @@ class EvacuateInstancesTask(base.MasakariTask): context, reserved_host.name, enable=True) # Sleep until nova-compute service is marked as enabled. - msg = _LI("Sleeping %(wait)s sec before starting recovery " - "thread until nova recognizes the node up.") + msg = ("Sleeping %(wait)s sec before starting recovery " + "thread until nova recognizes the node up.") LOG.info(msg, { 'wait': CONF.wait_period_after_service_update}) eventlet.sleep(CONF.wait_period_after_service_update) diff --git a/masakari/engine/drivers/taskflow/instance_failure.py b/masakari/engine/drivers/taskflow/instance_failure.py index ea2a422e..e8e866c3 100644 --- a/masakari/engine/drivers/taskflow/instance_failure.py +++ b/masakari/engine/drivers/taskflow/instance_failure.py @@ -24,7 +24,7 @@ from taskflow.patterns import linear_flow import masakari.conf from masakari.engine.drivers.taskflow import base from masakari import exception -from masakari.i18n import _, _LI +from masakari.i18n import _ CONF = masakari.conf.CONF @@ -51,8 +51,8 @@ class StopInstanceTask(base.MasakariTask): if not CONF.instance_failure.process_all_instances and not ( strutils.bool_from_string( instance.metadata.get('HA_Enabled', False))): - LOG.info(_LI("Skipping recovery for instance: %s as it is " - "not Ha_Enabled."), instance_uuid) + LOG.info("Skipping recovery for instance: %s as it is " + "not Ha_Enabled.", instance_uuid) raise exception.SkipInstanceRecoveryException() vm_state = getattr(instance, 'OS-EXT-STS:vm_state') diff --git a/masakari/engine/drivers/taskflow/process_failure.py b/masakari/engine/drivers/taskflow/process_failure.py index f4cb3439..d32a87ef 100644 --- a/masakari/engine/drivers/taskflow/process_failure.py +++ b/masakari/engine/drivers/taskflow/process_failure.py @@ -23,7 +23,7 @@ from taskflow.patterns import linear_flow import masakari.conf from masakari.engine.drivers.taskflow import base from masakari import exception -from masakari.i18n import _, _LI +from masakari.i18n import _ CONF = masakari.conf.CONF @@ -46,8 +46,8 @@ class DisableComputeNodeTask(base.MasakariTask): # disable compute node on given host self.novaclient.enable_disable_service(context, host_name) else: - LOG.info(_LI("Skipping recovery for process: %s as it is " - "already disabled."), + LOG.info("Skipping recovery for process: %s as it is " + "already disabled.", process_name) diff --git a/masakari/engine/manager.py b/masakari/engine/manager.py index c008f410..58db9749 100644 --- a/masakari/engine/manager.py +++ b/masakari/engine/manager.py @@ -31,7 +31,6 @@ import masakari.conf from masakari.engine import driver from masakari.engine import instance_events as virt_events from masakari import exception -from masakari.i18n import _LE, _LI, _LW from masakari import manager from masakari import objects from masakari.objects import fields @@ -61,14 +60,13 @@ class MasakariManager(manager.Manager): process_name = notification.payload.get('process_name') if notification_event.upper() == 'STARTED': - LOG.info(_LI("Notification type '%(type)s' received for host " - "'%(host_uuid)s': '%(process_name)s' has been " - "%(event)s."), { - 'type': notification.type, - 'host_uuid': notification.source_host_uuid, - 'process_name': process_name, - 'event': notification_event - }) + LOG.info("Notification type '%(type)s' received for host " + "'%(host_uuid)s': '%(process_name)s' has been " + "%(event)s.", + {'type': notification.type, + 'host_uuid': notification.source_host_uuid, + 'process_name': process_name, + 'event': notification_event}) elif notification_event.upper() == 'STOPPED': host_obj = objects.Host.get_by_uuid( context, notification.source_host_uuid) @@ -91,21 +89,20 @@ class MasakariManager(manager.Manager): exception.ProcessRecoveryFailureException): notification_status = fields.NotificationStatus.ERROR else: - LOG.warning(_LW("Invalid event: %(event)s received for " - "notification type: %(notification_type)s"), { - 'event': notification_event, - 'notification_type': notification.type - }) + LOG.warning("Invalid event: %(event)s received for " + "notification type: %(notification_type)s", + {'event': notification_event, + 'notification_type': notification.type}) notification_status = fields.NotificationStatus.IGNORED return notification_status def _handle_notification_type_instance(self, context, notification): if not virt_events.is_valid_event(notification.payload): - LOG.info(_LI("Notification '%(uuid)s' received with payload " - "%(payload)s is ignored."), { - "uuid": notification.notification_uuid, - "payload": notification.payload}) + LOG.info("Notification '%(uuid)s' received with payload " + "%(payload)s is ignored.", + {"uuid": notification.notification_uuid, + "payload": notification.payload}) return fields.NotificationStatus.IGNORED notification_status = fields.NotificationStatus.FINISHED @@ -126,12 +123,11 @@ class MasakariManager(manager.Manager): notification_event = notification.payload.get('event') if notification_event.upper() == 'STARTED': - LOG.info(_LI("Notification type '%(type)s' received for host " - "'%(host_uuid)s' has been %(event)s."), { - 'type': notification.type, - 'host_uuid': notification.source_host_uuid, - 'event': notification_event - }) + LOG.info("Notification type '%(type)s' received for host " + "'%(host_uuid)s' has been %(event)s.", + {'type': notification.type, + 'host_uuid': notification.source_host_uuid, + 'event': notification_event}) elif notification_event.upper() == 'STOPPED': host_obj = objects.Host.get_by_uuid( context, notification.source_host_uuid) @@ -170,11 +166,10 @@ class MasakariManager(manager.Manager): exception.MasakariException): notification_status = fields.NotificationStatus.ERROR else: - LOG.warning(_LW("Invalid event: %(event)s received for " - "notification type: %(type)s"), { - 'event': notification_event, - 'type': notification.type - }) + LOG.warning("Invalid event: %(event)s received for " + "notification type: %(type)s", + {'event': notification_event, + 'type': notification.type}) notification_status = fields.NotificationStatus.IGNORED return notification_status @@ -182,11 +177,10 @@ class MasakariManager(manager.Manager): def _process_notification(self, context, notification): @utils.synchronized(notification.source_host_uuid, blocking=True) def do_process_notification(notification): - LOG.info(_LI('Processing notification %(notification_uuid)s of ' - 'type: %(type)s'), { - 'notification_uuid': notification.notification_uuid, - 'type': notification.type - }) + LOG.info('Processing notification %(notification_uuid)s of ' + 'type: %(type)s', + {'notification_uuid': notification.notification_uuid, + 'type': notification.type}) update_data = { 'status': fields.NotificationStatus.RUNNING, @@ -204,11 +198,10 @@ class MasakariManager(manager.Manager): notification_status = self._handle_notification_type_host( context, notification) - LOG.info(_LI("Notification %(notification_uuid)s exits with " - "status: %(status)s."), { - 'notification_uuid': notification.notification_uuid, - 'status': notification_status - }) + LOG.info("Notification %(notification_uuid)s exits with " + "status: %(status)s.", + {'notification_uuid': notification.notification_uuid, + 'status': notification_status}) update_data = { 'status': notification_status @@ -253,10 +246,9 @@ class MasakariManager(manager.Manager): notification_db.update(update_data) notification_db.save() - LOG.error(_LE( + LOG.error( "Periodic task 'process_unfinished_notifications': " "Notification %(notification_uuid)s exits with " - "status: %(status)s."), { - 'notification_uuid': notification.notification_uuid, - 'status': notification_status - }) + "status: %(status)s.", + {'notification_uuid': notification.notification_uuid, + 'status': notification_status}) diff --git a/masakari/exception.py b/masakari/exception.py index 649bd96e..eb587e43 100644 --- a/masakari/exception.py +++ b/masakari/exception.py @@ -33,7 +33,7 @@ import webob.exc from webob import util as woutil import masakari.conf -from masakari.i18n import _, _LE +from masakari.i18n import _ from masakari import safe_utils LOG = logging.getLogger(__name__) @@ -58,7 +58,7 @@ class ConvertedException(webob.exc.WSGIHTTPException): try: self.title = woutil.status_reasons[self.code] except KeyError: - msg = _LE("Improper or unknown HTTP status code used: %d") + msg = "Improper or unknown HTTP status code used: %d" LOG.error(msg, code) self.title = woutil.status_generic_reasons[self.code // 100] self.explanation = explanation @@ -137,7 +137,7 @@ class MasakariException(Exception): exc_info = sys.exc_info() # kwargs doesn't match a variable in the message # log the issue and the kwargs - LOG.exception(_LE('Exception in string format operation')) + LOG.exception('Exception in string format operation') for name, value in kwargs.items(): LOG.error("%s: %s" % (name, value)) # noqa diff --git a/masakari/hacking/checks.py b/masakari/hacking/checks.py index bb627b21..72c54496 100644 --- a/masakari/hacking/checks.py +++ b/masakari/hacking/checks.py @@ -15,7 +15,6 @@ import re -import pep8 """ Guidelines for writing new hacking checks @@ -70,14 +69,6 @@ asse_true_false_with_in_or_not_in_spaces = re.compile( r"[][.'\", ])+[\[|'|\"](, .*)?\)") asse_raises_regexp = re.compile(r"assertRaisesRegexp\(") conf_attribute_set_re = re.compile(r"CONF\.[a-z0-9_.]+\s*=\s*\w") -log_translation = re.compile( - r"(.)*LOG\.(audit|error|critical)\(\s*('|\")") -log_translation_info = re.compile( - r"(.)*LOG\.(info)\(\s*(_\(|'|\")") -log_translation_exception = re.compile( - r"(.)*LOG\.(exception)\(\s*(_\(|'|\")") -log_translation_LW = re.compile( - r"(.)*LOG\.(warning|warn)\(\s*(_\(|'|\")") translated_log = re.compile( r"(.)*LOG\.(audit|error|info|critical|exception)" "\(\s*_\(\s*('|\")") @@ -222,27 +213,6 @@ def no_setting_conf_directly_in_tests(logical_line, filename): "instead") -def validate_log_translations(logical_line, physical_line, filename): - # Translations are not required in the test directory - if "masakari/tests" in filename: - return - if pep8.noqa(physical_line): - return - msg = "M311: LOG.info messages require translations `_LI()`!" - if log_translation_info.match(logical_line): - yield (0, msg) - msg = "M312: LOG.exception messages require translations `_LE()`!" - if log_translation_exception.match(logical_line): - yield (0, msg) - msg = ("M313: LOG.warning, LOG.warn messages require " - "translations `_LW()`!") - if log_translation_LW.match(logical_line): - yield (0, msg) - msg = "M314: Log messages require translations!" - if log_translation.match(logical_line): - yield (0, msg) - - def no_mutable_default_args(logical_line): msg = "M315: Method's default argument shouldn't be mutable!" if mutable_default_args.match(logical_line): @@ -469,7 +439,6 @@ def factory(register): register(assert_raises_regexp) register(no_translate_debug_logs) register(no_setting_conf_directly_in_tests) - register(validate_log_translations) register(no_mutable_default_args) register(check_explicit_underscore_import) register(use_jsonutils) diff --git a/masakari/i18n.py b/masakari/i18n.py index 5ec34d14..c57f6c91 100644 --- a/masakari/i18n.py +++ b/masakari/i18n.py @@ -27,16 +27,6 @@ _translators = oslo_i18n.TranslatorFactory(domain=DOMAIN) # The primary translation function using the well-known name "_" _ = _translators.primary -# Translators for log levels. -# -# The abbreviated names are meant to reflect the usual use of a short -# name like '_'. The "L" is for "log" and the other letter comes from -# the level. -_LI = _translators.log_info -_LW = _translators.log_warning -_LE = _translators.log_error -_LC = _translators.log_critical - def translate(value, user_locale): return oslo_i18n.translate(value, user_locale) diff --git a/masakari/service.py b/masakari/service.py index 50eff80a..ba5168f1 100644 --- a/masakari/service.py +++ b/masakari/service.py @@ -28,7 +28,7 @@ from oslo_utils import importutils import masakari.conf from masakari import context from masakari import exception -from masakari.i18n import _, _LE, _LI +from masakari.i18n import _ from masakari.objects import base as objects_base from masakari import rpc from masakari import utils @@ -79,7 +79,7 @@ class Service(service.Service): def start(self): verstr = version.version_string_with_package() - LOG.info(_LI('Starting %(topic)s (version %(version)s)'), { + LOG.info('Starting %(topic)s (version %(version)s)', { 'topic': self.topic, 'version': verstr }) @@ -178,7 +178,7 @@ class Service(service.Service): with utils.tempdir(): pass except Exception as e: - LOG.error(_LE('Temporary directory is invalid: %s'), e) + LOG.error('Temporary directory is invalid: %s', e) sys.exit(1) def reset(self): diff --git a/masakari/tests/unit/test_hacking.py b/masakari/tests/unit/test_hacking.py index 3f208d8f..aaff7249 100644 --- a/masakari/tests/unit/test_hacking.py +++ b/masakari/tests/unit/test_hacking.py @@ -218,32 +218,6 @@ class HackingTestCase(test.NoDBTestCase): self.assertEqual(len(list(checks.no_setting_conf_directly_in_tests( "CONF.option = 1", "masakari/compute/foo.py"))), 0) - def test_log_translations(self): - logs = ['audit', 'error', 'info', 'warning', 'critical', 'warn', - 'exception'] - levels = ['_LI', '_LW', '_LE', '_LC'] - debug = "LOG.debug('OK')" - self.assertEqual( - 0, len(list(checks.validate_log_translations(debug, debug, 'f')))) - for log in logs: - bad = 'LOG.%s("Bad")' % log - self.assertEqual(1, - len(list( - checks.validate_log_translations(bad, bad, 'f')))) - ok = "LOG.%s('OK') # noqa" % log - self.assertEqual(0, - len(list( - checks.validate_log_translations(ok, ok, 'f')))) - ok = "LOG.%s(variable)" % log - self.assertEqual(0, - len(list( - checks.validate_log_translations(ok, ok, 'f')))) - for level in levels: - ok = "LOG.%s(%s('OK'))" % (log, level) - self.assertEqual(0, - len(list( - checks.validate_log_translations(ok, ok, 'f')))) - def test_no_mutable_default_args(self): self.assertEqual(1, len(list(checks.no_mutable_default_args( "def get_info_from_bdm(virt_type, bdm, mapping=[])")))) @@ -271,7 +245,7 @@ class HackingTestCase(test.NoDBTestCase): "msg = _('My message')", "masakari/tests/other_files.py"))), 0) self.assertEqual(len(list(checks.check_explicit_underscore_import( - "from masakari.i18n import _, _LW", + "from masakari.i18n import _", "masakari/tests/other_files2.py"))), 0) self.assertEqual(len(list(checks.check_explicit_underscore_import( "msg = _('My message')", @@ -485,18 +459,18 @@ class HackingTestCase(test.NoDBTestCase): def test_check_delayed_string_interpolation(self): checker = checks.check_delayed_string_interpolation code = """ - msg_w = _LW('Test string (%s)') - msg_i = _LI('Test string (%s)') + msg_w = ('Test string (%s)') + msg_i = 'Test string (%s)' value = 'test' - LOG.error(_LE("Test string (%s)") % value) + LOG.error(("Test string (%s)") % value) LOG.warning(msg_w % 'test%string') LOG.info(msg_i % "test%string%info") LOG.critical( - _LC('Test string (%s)') % value, + ('Test string (%s)') % value, instance=instance) - LOG.exception(_LE(" 'Test quotation %s' \"Test\"") % 'test') + LOG.exception((" 'Test quotation %s' \"Test\"") % 'test') LOG.debug(' "Test quotation %s" \'Test\'' % "test") LOG.debug('Tesing %(test)s' % {'test': ','.join( @@ -504,28 +478,28 @@ class HackingTestCase(test.NoDBTestCase): for name, value in test.items()])}) """ - expected_errors = [(5, 34, 'M330'), (6, 18, 'M330'), (7, 15, 'M330'), - (10, 28, 'M330'), (12, 49, 'M330'), + expected_errors = [(5, 31, 'M330'), (6, 18, 'M330'), (7, 15, 'M330'), + (10, 25, 'M330'), (12, 46, 'M330'), (13, 40, 'M330'), (14, 28, 'M330')] self._assert_has_errors(code, checker, expected_errors=expected_errors) self._assert_has_no_errors( code, checker, filename='masakari/tests/unit/test_hacking.py') code = """ - msg_w = _LW('Test string (%s)') - msg_i = _LI('Test string (%s)') + msg_w = ('Test string (%s)') + msg_i = 'Test string (%s)' value = 'test' - LOG.error(_LE("Test string (%s)"), value) - LOG.error(_LE("Test string (%s)") % value) # noqa - LOG.warn(_LW('Test string (%s)'), + LOG.error(("Test string (%s)"), value) + LOG.error(("Test string (%s)") % value) # noqa + LOG.warn(('Test string (%s)'), value) LOG.info(msg_i, "test%string%info") LOG.critical( - _LC('Test string (%s)'), value, + ('Test string (%s)'), value, instance=instance) - LOG.exception(_LE(" 'Test quotation %s' \"Test\""), 'test') + LOG.exception((" 'Test quotation %s' \"Test\""), 'test') LOG.debug(' "Test quotation %s" \'Test\'', "test") LOG.debug('Tesing %(test)s', {'test': ','.join( diff --git a/masakari/utils.py b/masakari/utils.py index 6f3655d2..01ac30cb 100644 --- a/masakari/utils.py +++ b/masakari/utils.py @@ -33,7 +33,7 @@ import six import masakari.conf from masakari import exception -from masakari.i18n import _, _LE +from masakari.i18n import _ from masakari import safe_utils @@ -238,7 +238,7 @@ def tempdir(**kwargs): try: shutil.rmtree(tmpdir) except OSError as e: - LOG.error(_LE('Could not remove tmpdir: %s'), e) + LOG.error('Could not remove tmpdir: %s', e) def validate_integer(value, name, min_value=None, max_value=None): diff --git a/masakari/version.py b/masakari/version.py index ddb046f1..ce58c42d 100644 --- a/masakari/version.py +++ b/masakari/version.py @@ -15,8 +15,6 @@ from pbr import version as pbr_version -from masakari.i18n import _LE - MASAKARI_VENDOR = "OpenStack Foundation" MASAKARI_PRODUCT = "OpenStack Masakari" MASAKARI_PACKAGE = None # OS distro package version suffix @@ -60,7 +58,7 @@ def _load_config(): MASAKARI_PACKAGE = cfg.get("Masakari", "package") except Exception as ex: LOG = logging.getLogger(__name__) - LOG.error(_LE("Failed to load %(cfgfile)s: %(ex)s"), + LOG.error("Failed to load %(cfgfile)s: %(ex)s", {'cfgfile': cfgfile, 'ex': ex}) diff --git a/masakari/wsgi.py b/masakari/wsgi.py index 0cbb2a9d..b50fc17f 100644 --- a/masakari/wsgi.py +++ b/masakari/wsgi.py @@ -34,7 +34,7 @@ import webob.exc import masakari.conf from masakari import exception -from masakari.i18n import _, _LE, _LI +from masakari.i18n import _ from masakari import utils CONF = masakari.conf.CONF @@ -94,12 +94,12 @@ class Server(service.ServiceBase): try: self._socket = eventlet.listen(bind_addr, family, backlog=backlog) except EnvironmentError: - LOG.error(_LE("Could not bind to %(host)s:%(port)d"), + LOG.error("Could not bind to %(host)s:%(port)d", {'host': host, 'port': port}) raise (self.host, self.port) = self._socket.getsockname()[0:2] - LOG.info(_LI("%(name)s listening on %(host)s:%(port)d"), + LOG.info("%(name)s listening on %(host)s:%(port)d", {'name': self.name, 'host': self.host, 'port': self.port}) def start(self): @@ -163,8 +163,8 @@ class Server(service.ServiceBase): **ssl_kwargs) except Exception: with excutils.save_and_reraise_exception(): - LOG.error(_LE("Failed to start %(name)s on %(host)s" - ":%(port)d with SSL support"), + LOG.error("Failed to start %(name)s on %(host)s" + ":%(port)d with SSL support", {'name': self.name, 'host': self.host, 'port': self.port}) @@ -203,7 +203,7 @@ class Server(service.ServiceBase): :returns: None """ - LOG.info(_LI("Stopping WSGI server.")) + LOG.info("Stopping WSGI server.") if self._server is not None: # Resize pool to stop new requests from being processed @@ -223,7 +223,7 @@ class Server(service.ServiceBase): self._pool.waitall() self._server.wait() except greenlet.GreenletExit: - LOG.info(_LI("WSGI server has stopped.")) + LOG.info("WSGI server has stopped.") class Request(webob.Request): @@ -490,5 +490,5 @@ class Loader(object): {'name': name, 'path': self.config_path}) return deploy.loadapp("config:%s" % self.config_path, name=name) except LookupError: - LOG.exception(_LE("Couldn't lookup app: %s"), name) + LOG.exception("Couldn't lookup app: %s", name) raise exception.PasteAppNotFound(name=name, path=self.config_path)