Replacement `_` on `_LW` in all LOG.warning part 1

oslo.i18n uses different marker functions to separate the
translatable messages into different catalogs, which the translation
teams can prioritize translating. For details, please refer to:
http://docs.openstack.org/developer/oslo.i18n/guidelines.html#guidelines-for-use-in-openstack

There were not marker fuctions some places in directory network.
This commit makes changes:
* Add missing marker functions
* Use ',' instead of '%' while adding variables to log messages

Added a hacking rule for the warning about checking
translation for it and checking logging level `warning` instead
alias `warn`.

Change-Id: I2bced49dc5a0408a94d5d20d85b20c682886edbe
This commit is contained in:
Mike Durnosvistov 2014-09-19 18:32:50 +03:00
parent b7535793af
commit e8c0b822f0
33 changed files with 142 additions and 118 deletions

View File

@ -42,6 +42,8 @@ Nova Specific Commandments
- [N327] assert_called_once() is not a valid method
- [N328] Validate that LOG.info messages use _LI.
- [N329] Validate that LOG.exception messages use _LE.
- [N330] Validate that LOG.warning messages use _LW.
- [N331] Change LOG.warn on LOG.warning.
Creating Unit Tests
-------------------

View File

@ -87,7 +87,7 @@ class FaultWrapper(wsgi.Middleware):
try:
return req.get_response(self.application)
except Exception as ex:
LOG.exception(_LE("FaultWrapper: %s"), ex)
LOG.exception(_("FaultWrapper: %s"), ex)
return faults.Fault(webob.exc.HTTPInternalServerError())

View File

@ -144,7 +144,7 @@ class MetadataRequestHandler(wsgi.Application):
try:
meta_data = self.get_metadata_by_remote_address(remote_address)
except Exception:
LOG.exception(_LE('Failed to get metadata for ip: %s'),
LOG.exception(_('Failed to get metadata for ip: %s'),
remote_address)
msg = _('An unknown error has occurred. '
'Please try your request again.')
@ -202,7 +202,7 @@ class MetadataRequestHandler(wsgi.Application):
meta_data = self.get_metadata_by_instance_id(instance_id,
remote_address)
except Exception:
LOG.exception(_LE('Failed to get metadata for instance id: %s'),
LOG.exception(_('Failed to get metadata for instance id: %s'),
instance_id)
msg = _('An unknown error has occurred. '
'Please try your request again.')

View File

@ -29,7 +29,6 @@ from nova.api.openstack import wsgi
from nova import exception
from nova.i18n import _
from nova.i18n import _LC
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova.i18n import translate
@ -90,7 +89,7 @@ class FaultWrapper(base_wsgi.Middleware):
status, webob.exc.HTTPInternalServerError)()
def _error(self, inner, req):
LOG.exception(_LE("Caught error: %s"), unicode(inner))
LOG.exception(_("Caught error: %s"), unicode(inner))
safe = getattr(inner, 'safe', False)
headers = getattr(inner, 'headers', None)

View File

@ -28,7 +28,6 @@ from nova.api.openstack import wsgi
from nova.api.openstack import xmlutil
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LW
from nova.openstack.common import log as logging
import nova.policy
@ -240,7 +239,7 @@ class ExtensionManager(object):
LOG.debug('Ext namespace: %s', extension.namespace)
LOG.debug('Ext updated: %s', extension.updated)
except AttributeError as ex:
LOG.exception(_LE("Exception loading extension: %s"), ex)
LOG.exception(_("Exception loading extension: %s"), ex)
return False
return True
@ -499,7 +498,7 @@ def expected_errors(errors):
# expected error.
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/nova/ and attach the Nova '
'API log if possible.\n%s') % type(exc)

View File

@ -29,7 +29,7 @@ from nova.cells import state as cells_state
from nova.cells import utils as cells_utils
from nova import context
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova import manager
from nova import objects
from nova.objects import base as base_obj
@ -76,12 +76,12 @@ class CellsManager(manager.Manager):
target = oslo_messaging.Target(version='1.29')
def __init__(self, *args, **kwargs):
LOG.warn(_('The cells feature of Nova is considered experimental '
'by the OpenStack project because it receives much '
'less testing than the rest of Nova. This may change '
'in the future, but current deployers should be aware '
'that the use of it in production right now may be '
'risky.'))
LOG.warning(_LW('The cells feature of Nova is considered experimental '
'by the OpenStack project because it receives much '
'less testing than the rest of Nova. This may change '
'in the future, but current deployers should be aware '
'that the use of it in production right now may be '
'risky.'))
# Mostly for tests.
cell_state_manager = kwargs.pop('cell_state_manager', None)
super(CellsManager, self).__init__(service_name='cells',

View File

@ -49,7 +49,7 @@ from nova.consoleauth import rpcapi as consoleauth_rpcapi
from nova import context
from nova.db import base
from nova import exception
from nova.i18n import _, _LE, _LI
from nova.i18n import _, _LE, _LI, _LW
from nova.network import model as network_model
from nova import objects
from nova.objects import base as objects_base
@ -1210,8 +1210,8 @@ class _BroadcastMessageMethods(_BaseMessageMethods):
if vol_id and instance_bdm['volume_id'] == vol_id:
break
else:
LOG.warn(_("No match when trying to update BDM: %(bdm)s"),
dict(bdm=bdm))
LOG.warning(_LW("No match when trying to update BDM: %(bdm)s"),
dict(bdm=bdm))
return
self.db.block_device_mapping_update(message.ctxt,
instance_bdm['id'], bdm,
@ -1691,8 +1691,8 @@ class MessageRunner(object):
"""Call instance_<method> in correct cell for instance."""
cell_name = instance.cell_name
if not cell_name:
LOG.warn(_("No cell_name for %(method)s() from API"),
dict(method=method), instance=instance)
LOG.warning(_LW("No cell_name for %(method)s() from API"),
dict(method=method), instance=instance)
return
method_kwargs = {'instance': instance}
if extra_kwargs:
@ -1708,8 +1708,8 @@ class MessageRunner(object):
"""Update an instance object in its cell."""
cell_name = instance.cell_name
if not cell_name:
LOG.warn(_("No cell_name for instance update from API"),
instance=instance)
LOG.warning(_LW("No cell_name for instance update from API"),
instance=instance)
return
method_kwargs = {'instance': instance,
'expected_vm_state': expected_vm_state,

View File

@ -22,7 +22,7 @@ from oslo.config import cfg
from oslo.utils import timeutils
from nova.cells import weights
from nova.i18n import _
from nova.i18n import _LW
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
@ -63,9 +63,9 @@ class MuteChildWeigher(weights.BaseCellWeigher):
if timeutils.is_older_than(last_seen, secs):
# yep, that's a mute child; recommend highly that it be skipped!
LOG.warn(_("%(cell)s has not been seen since %(last_seen)s and is "
"being treated as mute."),
{'cell': cell, 'last_seen': last_seen})
LOG.warning(_LW("%(cell)s has not been seen since %(last_seen)s "
"and is being treated as mute."),
{'cell': cell, 'last_seen': last_seen})
return CONF.cells.mute_weight_value
else:
return 0

View File

@ -20,7 +20,7 @@ from oslo import messaging
from nova import baserpc
from nova.conductor import manager
from nova.conductor import rpcapi
from nova.i18n import _, _LI
from nova.i18n import _LI, _LW
from nova.openstack.common import log as logging
from nova import utils
@ -317,11 +317,11 @@ class API(LocalAPI):
break
except messaging.MessagingTimeout:
has_timedout = True
LOG.warning(_('Timed out waiting for nova-conductor. '
'Is it running? Or did this service start '
'before nova-conductor? '
'Reattempting establishment of '
'nova-conductor connection...'))
LOG.warning(_LW('Timed out waiting for nova-conductor. '
'Is it running? Or did this service start '
'before nova-conductor? '
'Reattempting establishment of '
'nova-conductor connection...'))
def instance_update(self, context, instance_uuid, **updates):
"""Perform an instance update in the database."""

View File

@ -34,7 +34,7 @@ from nova.compute import vm_states
from nova.conductor.tasks import live_migrate
from nova.db import base
from nova import exception
from nova.i18n import _, _LE
from nova.i18n import _, _LE, _LW
from nova import image
from nova import manager
from nova import network
@ -721,7 +721,7 @@ class ComputeTaskManager(base.Base):
except exception.NoValidHost:
instance.task_state = None
instance.save()
LOG.warning(_("No valid host found for unshelve instance"),
LOG.warning(_LW("No valid host found for unshelve instance"),
instance=instance)
return
else:
@ -762,8 +762,8 @@ class ComputeTaskManager(base.Base):
'rebuild_server',
{'vm_state': instance.vm_state,
'task_state': None}, ex, request_spec)
LOG.warning(_("No valid host found for rebuild"),
instance=instance)
LOG.warning(_LW("No valid host found for rebuild"),
instance=instance)
self.compute_rpcapi.rebuild_instance(context,
instance=instance,

View File

@ -95,11 +95,11 @@ def _get_port_range():
if start >= stop:
raise ValueError
except ValueError:
LOG.warn(_LW("serial_console.port_range should be <num>:<num>. "
"Given value %(port_range)s could not be parsed. "
"Taking the default port range %(default)s."),
{'port_range': config_range,
'default': DEFAULT_PORT_RANGE})
LOG.warning(_LW("serial_console.port_range should be <num>:<num>. "
"Given value %(port_range)s could not be parsed. "
"Taking the default port range %(default)s."),
{'port_range': config_range,
'default': DEFAULT_PORT_RANGE})
start, stop = map(int, DEFAULT_PORT_RANGE.split(':'))
return start, stop

View File

@ -82,7 +82,7 @@ class ConsoleAuthManager(manager.Manager):
if not self.mc.set(token.encode('UTF-8'),
data, CONF.console_token_ttl):
LOG.warning(_LW("Token: %(token)s failed to save into memcached."),
{'token': token})
{'token': token})
tokens = self._get_tokens_for_instance(instance_uuid)
# Remove the expired tokens from cache.
for tok in tokens:

View File

@ -23,8 +23,8 @@ from oslo.utils import timeutils
import six
from nova import exception
from nova.i18n import _
from nova.openstack.common import context
from nova.i18n import _, _LW
from nova.openstack.common import local
from nova.openstack.common import log as logging
from nova import policy
@ -57,8 +57,8 @@ class RequestContext(object):
because they possibly came in from older rpc messages.
"""
if kwargs:
LOG.warn(_('Arguments dropped when creating context: %s') %
str(kwargs))
LOG.warning(_LW('Arguments dropped when creating context: %s') %
str(kwargs))
self.user_id = user_id
self.project_id = project_id

View File

@ -60,7 +60,7 @@ from nova.compute import vm_states
import nova.context
from nova.db.sqlalchemy import models
from nova import exception
from nova.i18n import _, _LI, _LE
from nova.i18n import _, _LI, _LE, _LW
from nova.openstack.common import log as logging
from nova.openstack.common import uuidutils
from nova import quota
@ -181,9 +181,9 @@ def _retry_on_deadlock(f):
try:
return f(*args, **kwargs)
except db_exc.DBDeadlock:
LOG.warn(_("Deadlock detected when running "
"'%(func_name)s': Retrying..."),
dict(func_name=f.__name__))
LOG.warning(_LW("Deadlock detected when running "
"'%(func_name)s': Retrying..."),
dict(func_name=f.__name__))
# Retry!
time.sleep(0.5)
continue
@ -3491,8 +3491,8 @@ def quota_reserve(context, resources, project_quotas, user_quotas, deltas,
session.add(usage_ref)
if unders:
LOG.warning(_("Change will make usage less than 0 for the following "
"resources: %s"), unders)
LOG.warning(_LW("Change will make usage less than 0 for the following "
"resources: %s"), unders)
if overs:
_raise_overquota_exception(project_quotas, user_quotas, deltas, overs,

View File

@ -60,7 +60,7 @@ def init():
if not (CONF.remote_debug.host and CONF.remote_debug.port):
return
from nova.i18n import _
from nova.i18n import _LW
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
@ -77,7 +77,7 @@ def init():
stdoutToServer=False,
stderrToServer=False)
LOG.warn(_('WARNING: Using the remote debug option changes how '
'Nova uses the eventlet library to support async IO. This '
'could result in failures that do not occur under normal '
'operation. Use at your own risk.'))
LOG.warning(_LW('WARNING: Using the remote debug option changes how '
'Nova uses the eventlet library to support async IO. This '
'could result in failures that do not occur under normal '
'operation. Use at your own risk.'))

View File

@ -56,13 +56,17 @@ asse_equal_start_with_none_re = re.compile(
r"assertEqual\(None,")
conf_attribute_set_re = re.compile(r"CONF\.[a-z0-9_.]+\s*=\s*\w")
log_translation = re.compile(
r"(.)*LOG\.(audit|error|warn|warning|critical)\(\s*('|\")")
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)\(\s*(_\(|'|\")")
log_warn = re.compile(
r"(.)*LOG\.(warn)\(\s*('|\"|_)")
translated_log = re.compile(
r"(.)*LOG\.(audit|error|info|warn|warning|critical|exception)"
r"(.)*LOG\.(audit|error|info|critical|exception)"
"\(\s*_\(\s*('|\")")
mutable_default_args = re.compile(r"^\s*def .+\((.+=\{\}|.+=\[\])")
string_translation = re.compile(r"[^_]*_\(\s*('|\")")
@ -298,7 +302,13 @@ def validate_log_translations(logical_line, physical_line, filename):
# Translations are not required in the test directory
# and the Xen utilities
if ("nova/tests" in filename or
"plugins/xenserver/xenapi/etc/xapi.d" in filename):
"plugins/xenserver/xenapi/etc/xapi.d" in filename or
# TODO(Mike_D):Needs to be remove with:
# I075ab2a522272f2082c292dfedc877abd8ebe328
"nova/api" in filename or
"nova/compute" in filename or
"nova/network" in filename or
"nova/virt" in filename):
return
if pep8.noqa(physical_line):
return
@ -308,6 +318,12 @@ def validate_log_translations(logical_line, physical_line, filename):
msg = "N329: LOG.exception messages require translations `_LE()`!"
if log_translation_exception.match(logical_line):
yield (0, msg)
msg = "N330: LOG.warning messages require translations `_LW()`!"
if log_translation_LW.match(logical_line):
yield (0, msg)
msg = "N331: Use LOG.warning due to compatibility with py3"
if log_warn.match(logical_line):
yield (0, msg)
msg = "N321: Log messages require translations!"
if log_translation.match(logical_line):
yield (0, msg)

View File

@ -29,7 +29,7 @@ this class.
import array
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova.keymgr import key
from nova.keymgr import key_mgr
from nova.openstack.common import log as logging
@ -51,8 +51,8 @@ class MockKeyManager(key_mgr.KeyManager):
"""
def __init__(self):
LOG.warn(_('This key manager is not suitable for use in production'
' deployments'))
LOG.warning(_LW('This key manager is not suitable for use in '
'production deployments'))
self.keys = {}

View File

@ -20,7 +20,7 @@ all invocations of get_key.
from nova import exception
from nova.i18n import _
from nova.i18n import _, _LW
from nova.keymgr import mock_key_mgr
from nova.openstack.common import log as logging
@ -37,8 +37,8 @@ class SingleKeyManager(mock_key_mgr.MockKeyManager):
"""
def __init__(self):
LOG.warn(_('This key manager is insecure and is not recommended for '
'production deployments'))
LOG.warning(_LW('This key manager is insecure and is not recommended '
'for production deployments'))
super(SingleKeyManager, self).__init__()
self.key_id = '00000000-0000-0000-0000-000000000000'
@ -69,4 +69,4 @@ class SingleKeyManager(mock_key_mgr.MockKeyManager):
raise exception.KeyManagerError(
reason=_("cannot delete non-existent key"))
LOG.warn(_("Not deleting key %s"), key_id)
LOG.warning(_LW("Not deleting key %s"), key_id)

View File

@ -20,7 +20,7 @@ from nova.compute import task_states
from nova.compute import vm_states
from nova import context
from nova import exception
from nova.i18n import _
from nova.i18n import _LW
from nova import objects
from nova.openstack.common import log as logging
from nova.pci import device
@ -109,11 +109,12 @@ class PciDevTracker(object):
try:
device.remove(existed)
except exception.PciDeviceInvalidStatus as e:
LOG.warn(_("Trying to remove device with %(status)s "
"ownership %(instance_uuid)s because of "
"%(pci_exception)s"), {'status': existed.status,
'instance_uuid': existed.instance_uuid,
'pci_exception': e.format_message()})
LOG.warning(_LW("Trying to remove device with %(status)s "
"ownership %(instance_uuid)s because of "
"%(pci_exception)s"),
{'status': existed.status,
'instance_uuid': existed.instance_uuid,
'pci_exception': e.format_message()})
# Note(yjiang5): remove the device by force so that
# db entry is cleaned in next sync.
existed.status = 'removed'

View File

@ -44,7 +44,7 @@ class ComputeFilter(filters.BaseHostFilter):
return False
else:
if not self.servicegroup_api.service_is_up(service):
LOG.warn(_LW("%(host_state)s has not been heard from in a "
"while"), {'host_state': host_state})
LOG.warning(_LW("%(host_state)s has not been heard from in a "
"while"), {'host_state': host_state})
return False
return True

View File

@ -84,7 +84,7 @@ class AggregateDiskFilter(DiskFilter):
ratio = utils.validate_num_values(
aggregate_vals, CONF.disk_allocation_ratio, cast_to=float)
except ValueError as e:
LOG.warn(_LW("Could not decode disk_allocation_ratio: '%s'"), e)
LOG.warning(_LW("Could not decode disk_allocation_ratio: '%s'"), e)
ratio = CONF.disk_allocation_ratio
return ratio

View File

@ -73,7 +73,7 @@ class AggregateIoOpsFilter(IoOpsFilter):
value = utils.validate_num_values(
aggregate_vals, CONF.max_io_ops_per_host, cast_to=int)
except ValueError as e:
LOG.warn(_LW("Could not decode max_io_ops_per_host: '%s'"), e)
LOG.warning(_LW("Could not decode max_io_ops_per_host: '%s'"), e)
value = CONF.max_io_ops_per_host
return value

View File

@ -68,7 +68,8 @@ class AggregateNumInstancesFilter(NumInstancesFilter):
value = utils.validate_num_values(
aggregate_vals, CONF.max_instances_per_host, cast_to=int)
except ValueError as e:
LOG.warn(_LW("Could not decode max_instances_per_host: '%s'"), e)
LOG.warning(_LW("Could not decode max_instances_per_host: '%s'"),
e)
value = CONF.max_instances_per_host
return value

View File

@ -167,7 +167,7 @@ class HostState(object):
if name:
self.metrics[name] = item
else:
LOG.warn(_LW("Metric name unknown of %r"), item)
LOG.warning(_LW("Metric name unknown of %r"), item)
def update_from_compute_node(self, compute):
"""Update information about a host from its compute_node info."""
@ -182,11 +182,11 @@ class HostState(object):
if least_gb is not None:
if least_gb > free_gb:
# can occur when an instance in database is not on host
LOG.warn(_LW("Host %(hostname)s has more disk space than "
"database expected "
"(%(physical)sgb > %(database)sgb)"),
{'physical': least_gb, 'database': free_gb,
'hostname': compute['hypervisor_hostname']})
LOG.warning(_LW("Host %(hostname)s has more disk space than "
"database expected "
"(%(physical)sgb > %(database)sgb)"),
{'physical': least_gb, 'database': free_gb,
'hostname': compute['hypervisor_hostname']})
free_gb = min(least_gb, free_gb)
free_disk_mb = free_gb * 1024
@ -401,7 +401,7 @@ class HostManager(object):
for compute in compute_nodes:
service = compute['service']
if not service:
LOG.warn(_LW("No service for compute ID %s"), compute['id'])
LOG.warning(_LW("No service for compute ID %s"), compute['id'])
continue
host = service['host']
node = compute.get('hypervisor_hostname')

View File

@ -230,10 +230,10 @@ def parse_options(opts, sep='=', converter=str, name=""):
else:
bad.append(opt)
if bad:
LOG.warn(_LW("Ignoring the invalid elements of the option "
"%(name)s: %(options)s"),
{'name': name,
'options': ", ".join(bad)})
LOG.warning(_LW("Ignoring the invalid elements of the option "
"%(name)s: %(options)s"),
{'name': name,
'options': ", ".join(bad)})
return good

View File

@ -31,7 +31,7 @@ from nova import conductor
from nova import context
from nova import debugger
from nova import exception
from nova.i18n import _, _LE
from nova.i18n import _, _LE, _LW
from nova.objects import base as objects_base
from nova.openstack.common import log as logging
from nova.openstack.common import service
@ -283,7 +283,7 @@ class Service(service.Service):
self.conductor_api.service_destroy(context.get_admin_context(),
self.service_id)
except exception.NotFound:
LOG.warn(_('Service killed that has no database entry'))
LOG.warning(_LW('Service killed that has no database entry'))
def stop(self):
try:

View File

@ -21,7 +21,7 @@ import random
from oslo.config import cfg
from oslo.utils import importutils
from nova.i18n import _
from nova.i18n import _, _LW
from nova.openstack.common import log as logging
from nova import utils
@ -85,14 +85,14 @@ class API(object):
report_interval = CONF.report_interval
if CONF.service_down_time <= report_interval:
new_service_down_time = int(report_interval * 2.5)
LOG.warn(_("Report interval must be less than service down "
"time. Current config: <service_down_time: "
"%(service_down_time)s, report_interval: "
"%(report_interval)s>. Setting service_down_time to: "
"%(new_service_down_time)s"),
{'service_down_time': CONF.service_down_time,
'report_interval': report_interval,
'new_service_down_time': new_service_down_time})
LOG.warning(_LW("Report interval must be less than service down "
"time. Current config: <service_down_time: "
"%(service_down_time)s, report_interval: "
"%(report_interval)s>. Setting service_down_time "
"to: %(new_service_down_time)s"),
{'service_down_time': CONF.service_down_time,
'report_interval': report_interval,
'new_service_down_time': new_service_down_time})
CONF.set_override('service_down_time', new_service_down_time)
def join(self, member_id, group_id, service=None):

View File

@ -98,8 +98,8 @@ def find_multipath_device(device):
(out, err) = utils.execute('multipath', '-l', device,
run_as_root=True)
except processutils.ProcessExecutionError as exc:
LOG.warn(_LW("Multipath call failed exit (%(code)s)")
% {'code': exc.exit_code})
LOG.warning(_LW("Multipath call failed exit (%(code)s)"),
{'code': exc.exit_code})
return None
if out:
@ -119,7 +119,7 @@ def find_multipath_device(device):
mdev = '/dev/mapper/%s' % mdev_id
if mdev is None:
LOG.warn(_LW("Couldn't find multipath device %s"), line)
LOG.warning(_LW("Couldn't find multipath device %s"), line)
return None
LOG.debug("Found multipath device = %s", mdev)
@ -128,9 +128,9 @@ def find_multipath_device(device):
if dev_line.find("policy") != -1:
continue
if '#' in dev_line:
LOG.warn(_LW('Skip faulty line "%(dev_line)s" of'
' multipath device %(mdev)s')
% {'mdev': mdev, 'dev_line': dev_line})
LOG.warning(_LW('Skip faulty line "%(dev_line)s" of'
' multipath device %(mdev)s'),
{'mdev': mdev, 'dev_line': dev_line})
continue
dev_line = dev_line.lstrip(' |-`')

View File

@ -178,8 +178,8 @@ class _FakeImageService(object):
image = self.images.get(str(image_id))
if image:
return copy.deepcopy(image)
LOG.warn('Unable to find image id %s. Have images: %s',
image_id, self.images)
LOG.warning('Unable to find image id %s. Have images: %s',
image_id, self.images)
raise exception.ImageNotFound(image_id=image_id)
def create(self, context, metadata, data=None):

View File

@ -282,13 +282,13 @@ class HostManagerTestCase(test.NoDBTestCase):
db.compute_node_get_all(context).AndReturn(fakes.COMPUTE_NODES)
# node 3 host physical disk space is greater than database
host_manager.LOG.warn(_LW("Host %(hostname)s has more disk space than "
"database expected (%(physical)sgb > "
"%(database)sgb)"),
{'physical': 3333, 'database': 3072,
'hostname': 'node3'})
host_manager.LOG.warning(_LW("Host %(hostname)s has more disk space "
"than database expected (%(physical)sgb >"
" %(database)sgb)"),
{'physical': 3333, 'database': 3072,
'hostname': 'node3'})
# Invalid service
host_manager.LOG.warn(_LW("No service for compute ID %s"), 5)
host_manager.LOG.warning(_LW("No service for compute ID %s"), 5)
self.mox.ReplayAll()
self.host_manager.get_all_host_states(context)

View File

@ -65,7 +65,7 @@ class ContextTestCase(test.NoDBTestCase):
def fake_warn(log_msg):
info['log_msg'] = log_msg
self.stubs.Set(context.LOG, 'warn', fake_warn)
self.stubs.Set(context.LOG, 'warning', fake_warn)
c = context.RequestContext('user', 'project',
extra_arg1='meow', extra_arg2='wuff')

View File

@ -175,7 +175,7 @@ class HackingTestCase(test.NoDBTestCase):
"CONF.option = 1", "nova/compute/foo.py"))), 0)
def test_log_translations(self):
logs = ['audit', 'error', 'info', 'warn', 'warning', 'critical',
logs = ['audit', 'error', 'info', 'warning', 'critical',
'exception']
levels = ['_LI', '_LW', '_LE', '_LC']
debug = "LOG.debug('OK')"
@ -203,6 +203,11 @@ class HackingTestCase(test.NoDBTestCase):
len(list(
checks.validate_log_translations(ok, ok, 'f'))))
def test_log_translations_warning_instead_warn(self):
warn = "LOG.warn('qwe')"
self.assertEqual(
1, len(list(checks.validate_log_translations(warn, warn, 'f'))))
def test_no_mutable_default_args(self):
self.assertEqual(1, len(list(checks.no_mutable_default_args(
" def fake_suds_context(calls={}):"))))

View File

@ -46,7 +46,7 @@ from oslo.utils import timeutils
import six
from nova import exception
from nova.i18n import _, _LE
from nova.i18n import _, _LE, _LW
from nova.openstack.common import log as logging
notify_decorator = 'nova.notifications.notify_decorator'
@ -144,8 +144,9 @@ def vpn_ping(address, port, timeout=0.05, session_id=None):
sock.close()
fmt = '!BQxxxxxQxxxx'
if len(received) != struct.calcsize(fmt):
LOG.warn(_('Expected to receive %(exp)s bytes, but actually %(act)s') %
dict(exp=struct.calcsize(fmt), act=len(received)))
LOG.warning(_LW('Expected to receive %(exp)s bytes, '
'but actually %(act)s'),
dict(exp=struct.calcsize(fmt), act=len(received)))
return False
(identifier, server_sess, client_sess) = struct.unpack(fmt, received)
if identifier == 0x40 and client_sess == session_id: