From 047cb6849354f4fdf8d365bd109a0ed56a77d200 Mon Sep 17 00:00:00 2001
From: Tang Chen <chen.tang@easystack.cn>
Date: Thu, 16 Jun 2016 20:01:15 +0800
Subject: [PATCH] Standardize logger usage

Use file logger for all command specific logs.

This patch also fixes some usage that doesn't
follow rules in:
http://docs.openstack.org/developer/oslo.i18n/guidelines.html

After this patch, all self.log and self.app.log
will be standardized to LOG().

NOTE: In shell.py, we got the log in class OpenStackShell,
      which is also known as self.app.log in other classes.
      This logger is used to record non-command-specific logs.
      So we leave it as-is.

Change-Id: I114f73ee6c7e84593d71e724bc1ad00d343c1896
Implements: blueprint log-usage
---
 openstackclient/common/availability_zone.py   | 20 ++++++-----
 openstackclient/common/extension.py           | 21 ++++++-----
 openstackclient/compute/v2/agent.py           | 12 ++++---
 openstackclient/compute/v2/flavor.py          | 22 ++++++------
 openstackclient/compute/v2/server.py          | 36 ++++++++++---------
 openstackclient/compute/v2/server_group.py    |  7 +++-
 openstackclient/compute/v2/server_image.py    | 10 +++---
 openstackclient/compute/v2/service.py         |  9 +++--
 openstackclient/identity/v2_0/project.py      |  7 +++-
 openstackclient/identity/v2_0/role.py         |  7 +++-
 openstackclient/identity/v2_0/service.py      |  8 +++--
 openstackclient/identity/v2_0/user.py         |  7 +++-
 openstackclient/identity/v3/domain.py         |  6 +++-
 .../identity/v3/federation_protocol.py        |  7 +++-
 openstackclient/identity/v3/group.py          |  6 +++-
 .../identity/v3/identity_provider.py          |  7 +++-
 openstackclient/identity/v3/mapping.py        |  6 +++-
 openstackclient/identity/v3/project.py        |  7 +++-
 openstackclient/identity/v3/role.py           |  6 +++-
 openstackclient/identity/v3/user.py           |  6 +++-
 openstackclient/image/v1/image.py             | 23 ++++++------
 openstackclient/image/v2/image.py             | 32 ++++++++---------
 openstackclient/network/common.py             | 18 ++++++----
 openstackclient/network/v2/address_scope.py   | 11 ++++--
 openstackclient/network/v2/port.py            |  6 ++--
 .../tests/compute/v2/test_service.py          | 15 ++++----
 26 files changed, 206 insertions(+), 116 deletions(-)

diff --git a/openstackclient/common/availability_zone.py b/openstackclient/common/availability_zone.py
index af161d1f61..89d77d1585 100644
--- a/openstackclient/common/availability_zone.py
+++ b/openstackclient/common/availability_zone.py
@@ -14,6 +14,7 @@
 """Availability Zone action implementations"""
 
 import copy
+import logging
 
 from novaclient import exceptions as nova_exceptions
 from osc_lib.command import command
@@ -23,6 +24,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _xform_common_availability_zone(az, zone_info):
     if hasattr(az, 'zoneState'):
         zone_info['zone_status'] = ('available' if az.zoneState['available']
@@ -136,11 +140,11 @@ class ListAvailabilityZone(command.Lister):
         try:
             data = volume_client.availability_zones.list()
         except Exception as e:
-            self.log.debug('Volume availability zone exception: ' + str(e))
+            LOG.debug('Volume availability zone exception: %s', e)
             if parsed_args.volume:
-                message = "Availability zones list not supported by " \
-                          "Block Storage API"
-                self.log.warning(message)
+                message = _("Availability zones list not supported by "
+                            "Block Storage API")
+                LOG.warning(message)
 
         result = []
         for zone in data:
@@ -154,11 +158,11 @@ class ListAvailabilityZone(command.Lister):
             network_client.find_extension('Availability Zone',
                                           ignore_missing=False)
         except Exception as e:
-            self.log.debug('Network availability zone exception: ' + str(e))
+            LOG.debug('Network availability zone exception: ', e)
             if parsed_args.network:
-                message = "Availability zones list not supported by " \
-                          "Network API"
-                self.log.warning(message)
+                message = _("Availability zones list not supported by "
+                            "Network API")
+                LOG.warning(message)
             return []
 
         result = []
diff --git a/openstackclient/common/extension.py b/openstackclient/common/extension.py
index 327fc2238c..de48001609 100644
--- a/openstackclient/common/extension.py
+++ b/openstackclient/common/extension.py
@@ -16,6 +16,7 @@
 """Extension action implementations"""
 
 import itertools
+import logging
 
 from osc_lib.command import command
 from osc_lib import utils
@@ -23,6 +24,9 @@ from osc_lib import utils
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class ListExtension(command.Lister):
     """List API extensions"""
 
@@ -80,24 +84,25 @@ class ListExtension(command.Lister):
             try:
                 data += identity_client.extensions.list()
             except Exception:
-                message = "Extensions list not supported by Identity API"
-                self.log.warning(message)
+                message = _("Extensions list not supported by Identity API")
+                LOG.warning(message)
 
         if parsed_args.compute or show_all:
             compute_client = self.app.client_manager.compute
             try:
                 data += compute_client.list_extensions.show_all()
             except Exception:
-                message = "Extensions list not supported by Compute API"
-                self.log.warning(message)
+                message = _("Extensions list not supported by Compute API")
+                LOG.warning(message)
 
         if parsed_args.volume or show_all:
             volume_client = self.app.client_manager.volume
             try:
                 data += volume_client.list_extensions.show_all()
             except Exception:
-                message = "Extensions list not supported by Block Storage API"
-                self.log.warning(message)
+                message = _("Extensions list not supported by "
+                            "Block Storage API")
+                LOG.warning(message)
 
         # Resource classes for the above
         extension_tuples = (
@@ -125,7 +130,7 @@ class ListExtension(command.Lister):
                     dict_tuples
                 )
             except Exception:
-                message = "Extensions list not supported by Network API"
-                self.log.warning(message)
+                message = _("Extensions list not supported by Network API")
+                LOG.warning(message)
 
         return (columns, extension_tuples)
diff --git a/openstackclient/compute/v2/agent.py b/openstackclient/compute/v2/agent.py
index ce6898c122..62be2424bf 100644
--- a/openstackclient/compute/v2/agent.py
+++ b/openstackclient/compute/v2/agent.py
@@ -15,6 +15,8 @@
 
 """Agent action implementations"""
 
+import logging
+
 from osc_lib.command import command
 from osc_lib import exceptions
 from osc_lib import utils
@@ -23,6 +25,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateAgent(command.ShowOne):
     """Create compute agent command"""
 
@@ -96,14 +101,13 @@ class DeleteAgent(command.Command):
                 compute_client.agents.delete(id)
             except Exception as e:
                 result += 1
-                self.app.log.error(_("Failed to delete agent with "
-                                   "ID '%(id)s': %(e)s")
-                                   % {'id': id, 'e': e})
+                LOG.error(_("Failed to delete agent with ID '%(id)s': %(e)s"),
+                          {'id': id, 'e': e})
 
         if result > 0:
             total = len(parsed_args.id)
             msg = (_("%(result)s of %(total)s agents failed "
-                   "to delete.") % {'result': result, 'total': total})
+                     "to delete.") % {'result': result, 'total': total})
             raise exceptions.CommandError(msg)
 
 
diff --git a/openstackclient/compute/v2/flavor.py b/openstackclient/compute/v2/flavor.py
index ab2bc85d0f..0a0d25c2de 100644
--- a/openstackclient/compute/v2/flavor.py
+++ b/openstackclient/compute/v2/flavor.py
@@ -15,6 +15,8 @@
 
 """Flavor action implementations"""
 
+import logging
+
 from osc_lib.cli import parseractions
 from osc_lib.command import command
 from osc_lib import exceptions
@@ -25,6 +27,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common as identity_common
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _find_flavor(compute_client, flavor):
     try:
         return compute_client.flavors.get(flavor)
@@ -282,8 +287,7 @@ class SetFlavor(command.Command):
             try:
                 flavor.set_keys(parsed_args.property)
             except Exception as e:
-                self.app.log.error(
-                    _("Failed to set flavor property: %s") % str(e))
+                LOG.error(_("Failed to set flavor property: %s"), e)
                 result += 1
 
         if parsed_args.project:
@@ -300,13 +304,12 @@ class SetFlavor(command.Command):
                     compute_client.flavor_access.add_tenant_access(
                         flavor.id, project_id)
             except Exception as e:
-                self.app.log.error(_("Failed to set flavor access to"
-                                     " project: %s") % str(e))
+                LOG.error(_("Failed to set flavor access to project: %s"), e)
                 result += 1
 
         if result > 0:
             raise exceptions.CommandError(_("Command Failed: One or more of"
-                                          " the operations failed"))
+                                            " the operations failed"))
 
 
 class ShowFlavor(command.ShowOne):
@@ -373,8 +376,7 @@ class UnsetFlavor(command.Command):
             try:
                 flavor.unset_keys(parsed_args.property)
             except Exception as e:
-                self.app.log.error(
-                    _("Failed to unset flavor property: %s") % str(e))
+                LOG.error(_("Failed to unset flavor property: %s"), e)
                 result += 1
 
         if parsed_args.project:
@@ -391,10 +393,10 @@ class UnsetFlavor(command.Command):
                     compute_client.flavor_access.remove_tenant_access(
                         flavor.id, project_id)
             except Exception as e:
-                self.app.log.error(_("Failed to remove flavor access from"
-                                     " project: %s") % str(e))
+                LOG.error(_("Failed to remove flavor access from project: %s"),
+                          e)
                 result += 1
 
         if result > 0:
             raise exceptions.CommandError(_("Command Failed: One or more of"
-                                          " the operations failed"))
+                                            " the operations failed"))
diff --git a/openstackclient/compute/v2/server.py b/openstackclient/compute/v2/server.py
index 42736d660f..7e4b0dc1f7 100644
--- a/openstackclient/compute/v2/server.py
+++ b/openstackclient/compute/v2/server.py
@@ -18,6 +18,7 @@
 import argparse
 import getpass
 import io
+import logging
 import os
 import sys
 
@@ -36,6 +37,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common as identity_common
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _format_servers_list_networks(networks):
     """Return a formatted string of a server's networks
 
@@ -521,8 +525,8 @@ class CreateServer(command.ShowOne):
             scheduler_hints=hints,
             config_drive=config_drive)
 
-        self.log.debug('boot_args: %s', boot_args)
-        self.log.debug('boot_kwargs: %s', boot_kwargs)
+        LOG.debug('boot_args: %s', boot_args)
+        LOG.debug('boot_kwargs: %s', boot_kwargs)
 
         # Wrap the call to catch exceptions in order to close files
         try:
@@ -543,8 +547,8 @@ class CreateServer(command.ShowOne):
             ):
                 sys.stdout.write('\n')
             else:
-                self.log.error(_('Error creating server: %s'),
-                               parsed_args.server_name)
+                LOG.error(_('Error creating server: %s'),
+                          parsed_args.server_name)
                 sys.stdout.write(_('Error creating server\n'))
                 raise SystemExit
 
@@ -612,8 +616,8 @@ class DeleteServer(command.Command):
                 ):
                     sys.stdout.write('\n')
                 else:
-                    self.log.error(_('Error deleting server: %s'),
-                                   server_obj.id)
+                    LOG.error(_('Error deleting server: %s'),
+                              server_obj.id)
                     sys.stdout.write(_('Error deleting server\n'))
                     raise SystemExit
 
@@ -762,7 +766,7 @@ class ListServer(command.Lister):
             'all_tenants': parsed_args.all_projects,
             'user_id': user_id,
         }
-        self.log.debug('search options: %s', search_opts)
+        LOG.debug('search options: %s', search_opts)
 
         if parsed_args.long:
             columns = (
@@ -939,8 +943,8 @@ class MigrateServer(command.Command):
             ):
                 sys.stdout.write(_('Complete\n'))
             else:
-                self.log.error(_('Error migrating server: %s'),
-                               server.id)
+                LOG.error(_('Error migrating server: %s'),
+                          server.id)
                 sys.stdout.write(_('Error migrating server\n'))
                 raise SystemExit
 
@@ -1015,8 +1019,8 @@ class RebootServer(command.Command):
             ):
                 sys.stdout.write(_('Complete\n'))
             else:
-                self.log.error(_('Error rebooting server: %s'),
-                               server.id)
+                LOG.error(_('Error rebooting server: %s'),
+                          server.id)
                 sys.stdout.write(_('Error rebooting server\n'))
                 raise SystemExit
 
@@ -1068,8 +1072,8 @@ class RebuildServer(command.ShowOne):
             ):
                 sys.stdout.write(_('Complete\n'))
             else:
-                self.log.error(_('Error rebuilding server: %s'),
-                               server.id)
+                LOG.error(_('Error rebuilding server: %s'),
+                          server.id)
                 sys.stdout.write(_('Error rebuilding server\n'))
                 raise SystemExit
 
@@ -1222,8 +1226,8 @@ class ResizeServer(command.Command):
                 ):
                     sys.stdout.write(_('Complete\n'))
                 else:
-                    self.log.error(_('Error resizing server: %s'),
-                                   server.id)
+                    LOG.error(_('Error resizing server: %s'),
+                              server.id)
                     sys.stdout.write(_('Error resizing server\n'))
                     raise SystemExit
         elif parsed_args.confirm:
@@ -1538,7 +1542,7 @@ class SshServer(command.Command):
         ip_address = _get_ip_address(server.addresses,
                                      parsed_args.address_type,
                                      ip_address_family)
-        self.log.debug("ssh command: %s", (cmd % (login, ip_address)))
+        LOG.debug("ssh command: %s", (cmd % (login, ip_address)))
         os.system(cmd % (login, ip_address))
 
 
diff --git a/openstackclient/compute/v2/server_group.py b/openstackclient/compute/v2/server_group.py
index 955b147e71..d51b1ec23e 100644
--- a/openstackclient/compute/v2/server_group.py
+++ b/openstackclient/compute/v2/server_group.py
@@ -15,6 +15,8 @@
 
 """Compute v2 Server Group action implementations"""
 
+import logging
+
 from osc_lib.command import command
 from osc_lib import exceptions
 from osc_lib import utils
@@ -22,6 +24,9 @@ from osc_lib import utils
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 _formatters = {
     'policies': utils.format_list,
     'members': utils.format_list,
@@ -95,7 +100,7 @@ class DeleteServerGroup(command.Command):
             # Catch all exceptions in order to avoid to block the next deleting
             except Exception as e:
                 result += 1
-                self.app.log.error(e)
+                LOG.error(e)
 
         if result > 0:
             total = len(parsed_args.server_group)
diff --git a/openstackclient/compute/v2/server_image.py b/openstackclient/compute/v2/server_image.py
index 85ee7f2d18..6f5a754699 100644
--- a/openstackclient/compute/v2/server_image.py
+++ b/openstackclient/compute/v2/server_image.py
@@ -15,6 +15,7 @@
 
 """Compute v2 Server action implementations"""
 
+import logging
 import sys
 
 from oslo_utils import importutils
@@ -26,6 +27,9 @@ from openstackclient.common import utils
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _show_progress(progress):
     if progress:
         sys.stdout.write('\rProgress: %s' % progress)
@@ -90,10 +94,8 @@ class CreateServerImage(command.ShowOne):
             ):
                 sys.stdout.write('\n')
             else:
-                self.log.error(
-                    _('Error creating server image: %s') %
-                    parsed_args.server,
-                )
+                LOG.error(_('Error creating server image: %s'),
+                          parsed_args.server)
                 raise exceptions.CommandError
 
         if self.app.client_manager._api_version['image'] == '1':
diff --git a/openstackclient/compute/v2/service.py b/openstackclient/compute/v2/service.py
index d10af2cad9..36917e2035 100644
--- a/openstackclient/compute/v2/service.py
+++ b/openstackclient/compute/v2/service.py
@@ -15,6 +15,8 @@
 
 """Service action implementations"""
 
+import logging
+
 from osc_lib.command import command
 from osc_lib import exceptions
 from osc_lib import utils
@@ -23,6 +25,9 @@ from openstackclient.i18n import _
 from openstackclient.i18n import _LE
 
 
+LOG = logging.getLogger(__name__)
+
+
 class DeleteService(command.Command):
     """Delete service command"""
 
@@ -171,7 +176,7 @@ class SetService(command.Command):
                         cs.disable(parsed_args.host, parsed_args.service)
         except Exception:
             status = "enabled" if enabled else "disabled"
-            self.log.error(_LE("Failed to set service status to %s"), status)
+            LOG.error(_LE("Failed to set service status to %s"), status)
             result += 1
 
         force_down = None
@@ -185,7 +190,7 @@ class SetService(command.Command):
                               force_down=force_down)
         except Exception:
             state = "down" if force_down else "up"
-            self.log.error(_LE("Failed to set service state to %s"), state)
+            LOG.error(_LE("Failed to set service state to %s"), state)
             result += 1
 
         if result > 0:
diff --git a/openstackclient/identity/v2_0/project.py b/openstackclient/identity/v2_0/project.py
index c4f730e0a7..6c5db13c68 100644
--- a/openstackclient/identity/v2_0/project.py
+++ b/openstackclient/identity/v2_0/project.py
@@ -15,6 +15,8 @@
 
 """Identity v2 Project action implementations"""
 
+import logging
+
 from keystoneauth1 import exceptions as ks_exc
 from osc_lib.cli import parseractions
 from osc_lib.command import command
@@ -24,6 +26,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateProject(command.ShowOne):
     """Create new project"""
 
@@ -87,7 +92,7 @@ class CreateProject(command.ShowOne):
                     identity_client.tenants,
                     parsed_args.name,
                 )
-                self.log.info(_('Returning existing project %s'), project.name)
+                LOG.info(_('Returning existing project %s'), project.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v2_0/role.py b/openstackclient/identity/v2_0/role.py
index 4c3fe6e236..6d06230c44 100644
--- a/openstackclient/identity/v2_0/role.py
+++ b/openstackclient/identity/v2_0/role.py
@@ -15,6 +15,8 @@
 
 """Identity v2 Role action implementations"""
 
+import logging
+
 from keystoneauth1 import exceptions as ks_exc
 from osc_lib.command import command
 from osc_lib import exceptions
@@ -24,6 +26,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class AddRole(command.ShowOne):
     """Add role to project:user"""
 
@@ -94,7 +99,7 @@ class CreateRole(command.ShowOne):
                     identity_client.roles,
                     parsed_args.role_name,
                 )
-                self.log.info(_('Returning existing role %s'), role.name)
+                LOG.info(_('Returning existing role %s'), role.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v2_0/service.py b/openstackclient/identity/v2_0/service.py
index 947f361cf3..413977ec15 100644
--- a/openstackclient/identity/v2_0/service.py
+++ b/openstackclient/identity/v2_0/service.py
@@ -16,6 +16,7 @@
 """Service action implementations"""
 
 import argparse
+import logging
 
 from osc_lib.command import command
 from osc_lib import exceptions
@@ -26,6 +27,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateService(command.ShowOne):
     """Create new service"""
 
@@ -69,8 +73,8 @@ class CreateService(command.ShowOne):
         # display deprecation message.
         elif type:
             name = type_or_name
-            self.log.warning(_('The argument --type is deprecated, use service'
-                               ' create --name <service-name> type instead.'))
+            LOG.warning(_('The argument --type is deprecated, use service'
+                          ' create --name <service-name> type instead.'))
         # If --name option is present the positional is handled as <type>.
         # Making --type optional is new, but back-compatible
         elif name:
diff --git a/openstackclient/identity/v2_0/user.py b/openstackclient/identity/v2_0/user.py
index 3ee2a65e55..80edfab605 100644
--- a/openstackclient/identity/v2_0/user.py
+++ b/openstackclient/identity/v2_0/user.py
@@ -15,6 +15,8 @@
 
 """Identity v2.0 User action implementations"""
 
+import logging
+
 from keystoneauth1 import exceptions as ks_exc
 from osc_lib.command import command
 from osc_lib import utils
@@ -23,6 +25,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateUser(command.ShowOne):
     """Create new user"""
 
@@ -103,7 +108,7 @@ class CreateUser(command.ShowOne):
                     identity_client.users,
                     parsed_args.name,
                 )
-                self.log.info(_('Returning existing user %s'), user.name)
+                LOG.info(_('Returning existing user %s'), user.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v3/domain.py b/openstackclient/identity/v3/domain.py
index 8eb7bc91de..001d520167 100644
--- a/openstackclient/identity/v3/domain.py
+++ b/openstackclient/identity/v3/domain.py
@@ -15,6 +15,7 @@
 
 """Identity v3 Domain action implementations"""
 
+import logging
 import sys
 
 from keystoneauth1 import exceptions as ks_exc
@@ -25,6 +26,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateDomain(command.ShowOne):
     """Create new domain"""
 
@@ -75,7 +79,7 @@ class CreateDomain(command.ShowOne):
             if parsed_args.or_show:
                 domain = utils.find_resource(identity_client.domains,
                                              parsed_args.name)
-                self.log.info(_('Returning existing domain %s'), domain.name)
+                LOG.info(_('Returning existing domain %s'), domain.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v3/federation_protocol.py b/openstackclient/identity/v3/federation_protocol.py
index 377ddcceec..094802455a 100644
--- a/openstackclient/identity/v3/federation_protocol.py
+++ b/openstackclient/identity/v3/federation_protocol.py
@@ -14,6 +14,8 @@
 
 """Identity v3 Protocols actions implementations"""
 
+import logging
+
 from osc_lib.command import command
 from osc_lib import utils
 import six
@@ -21,6 +23,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateProtocol(command.ShowOne):
     """Create new federation protocol"""
 
@@ -145,7 +150,7 @@ class SetProtocol(command.Command):
         identity_client = self.app.client_manager.identity
 
         if not parsed_args.mapping:
-            self.app.log.error(_("No changes requested"))
+            LOG.error(_("No changes requested"))
             return
 
         protocol = identity_client.federation.protocols.update(
diff --git a/openstackclient/identity/v3/group.py b/openstackclient/identity/v3/group.py
index fb0a25b973..8351fe640f 100644
--- a/openstackclient/identity/v3/group.py
+++ b/openstackclient/identity/v3/group.py
@@ -15,6 +15,7 @@
 
 """Group action implementations"""
 
+import logging
 import sys
 
 from keystoneauth1 import exceptions as ks_exc
@@ -26,6 +27,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common
 
 
+LOG = logging.getLogger(__name__)
+
+
 class AddUserToGroup(command.Command):
     """Add user to group"""
 
@@ -161,7 +165,7 @@ class CreateGroup(command.ShowOne):
                 group = utils.find_resource(identity_client.groups,
                                             parsed_args.name,
                                             domain_id=domain)
-                self.log.info(_('Returning existing group %s'), group.name)
+                LOG.info(_('Returning existing group %s'), group.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v3/identity_provider.py b/openstackclient/identity/v3/identity_provider.py
index 0b530a26fc..5c638f9b6b 100644
--- a/openstackclient/identity/v3/identity_provider.py
+++ b/openstackclient/identity/v3/identity_provider.py
@@ -13,6 +13,8 @@
 
 """Identity v3 IdentityProvider action implementations"""
 
+import logging
+
 from osc_lib.command import command
 from osc_lib import utils
 import six
@@ -20,6 +22,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateIdentityProvider(command.ShowOne):
     """Create new identity provider"""
 
@@ -169,7 +174,7 @@ class SetIdentityProvider(command.Command):
                 not parsed_args.remote_id and
                 not parsed_args.remote_id_file and
                 not parsed_args.description):
-            self.log.error(_('No changes requested'))
+            LOG.error(_('No changes requested'))
             return (None, None)
 
         # Always set remote_ids if either is passed in
diff --git a/openstackclient/identity/v3/mapping.py b/openstackclient/identity/v3/mapping.py
index 5937474e76..74ead2281a 100644
--- a/openstackclient/identity/v3/mapping.py
+++ b/openstackclient/identity/v3/mapping.py
@@ -16,6 +16,7 @@
 """Identity v3 federation mapping action implementations"""
 
 import json
+import logging
 
 from osc_lib.command import command
 from osc_lib import exceptions
@@ -25,6 +26,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 class _RulesReader(object):
     """Helper class capable of reading rules from files"""
 
@@ -159,7 +163,7 @@ class SetMapping(command.Command, _RulesReader):
         identity_client = self.app.client_manager.identity
 
         if not parsed_args.rules:
-            self.app.log.error(_("No changes requested"))
+            LOG.error(_("No changes requested"))
             return
 
         rules = self._read_rules(parsed_args.rules)
diff --git a/openstackclient/identity/v3/project.py b/openstackclient/identity/v3/project.py
index 6145dcf14c..4db5bef132 100644
--- a/openstackclient/identity/v3/project.py
+++ b/openstackclient/identity/v3/project.py
@@ -15,6 +15,8 @@
 
 """Project action implementations"""
 
+import logging
+
 from keystoneauth1 import exceptions as ks_exc
 from osc_lib.cli import parseractions
 from osc_lib.command import command
@@ -25,6 +27,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateProject(command.ShowOne):
     """Create new project"""
 
@@ -111,7 +116,7 @@ class CreateProject(command.ShowOne):
                 project = utils.find_resource(identity_client.projects,
                                               parsed_args.name,
                                               domain_id=domain)
-                self.log.info(_('Returning existing project %s'), project.name)
+                LOG.info(_('Returning existing project %s'), project.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v3/role.py b/openstackclient/identity/v3/role.py
index 1bb2758587..965ca3f59f 100644
--- a/openstackclient/identity/v3/role.py
+++ b/openstackclient/identity/v3/role.py
@@ -15,6 +15,7 @@
 
 """Identity v3 Role action implementations"""
 
+import logging
 import sys
 
 from keystoneauth1 import exceptions as ks_exc
@@ -26,6 +27,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _add_identity_and_resource_options_to_parser(parser):
     domain_or_project = parser.add_mutually_exclusive_group()
     domain_or_project.add_argument(
@@ -165,7 +169,7 @@ class CreateRole(command.ShowOne):
             if parsed_args.or_show:
                 role = utils.find_resource(identity_client.roles,
                                            parsed_args.name)
-                self.log.info(_('Returning existing role %s'), role.name)
+                LOG.info(_('Returning existing role %s'), role.name)
             else:
                 raise e
 
diff --git a/openstackclient/identity/v3/user.py b/openstackclient/identity/v3/user.py
index 39125e2cd2..96dd42449c 100644
--- a/openstackclient/identity/v3/user.py
+++ b/openstackclient/identity/v3/user.py
@@ -16,6 +16,7 @@
 """Identity v3 User action implementations"""
 
 import copy
+import logging
 import sys
 
 from keystoneauth1 import exceptions as ks_exc
@@ -27,6 +28,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common
 
 
+LOG = logging.getLogger(__name__)
+
+
 class CreateUser(command.ShowOne):
     """Create new user"""
 
@@ -122,7 +126,7 @@ class CreateUser(command.ShowOne):
                 user = utils.find_resource(identity_client.users,
                                            parsed_args.name,
                                            domain_id=domain_id)
-                self.log.info(_('Returning existing user %s'), user.name)
+                LOG.info(_('Returning existing user %s'), user.name)
             else:
                 raise e
 
diff --git a/openstackclient/image/v1/image.py b/openstackclient/image/v1/image.py
index 1644809d76..27467b0c28 100644
--- a/openstackclient/image/v1/image.py
+++ b/openstackclient/image/v1/image.py
@@ -17,6 +17,7 @@
 
 import argparse
 import io
+import logging
 import os
 import sys
 
@@ -39,6 +40,9 @@ DEFAULT_CONTAINER_FORMAT = 'bare'
 DEFAULT_DISK_FORMAT = 'raw'
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _format_visibility(data):
     """Return a formatted visibility string
 
@@ -189,10 +193,8 @@ class CreateImage(command.ShowOne):
         image_client = self.app.client_manager.image
 
         if getattr(parsed_args, 'owner', None) is not None:
-            self.log.warning(_(
-                'The --owner option is deprecated, '
-                'please use --project instead.'
-            ))
+            LOG.warning(_('The --owner option is deprecated, '
+                          'please use --project instead.'))
 
         # Build an attribute dict from the parsed args, only include
         # attributes that were actually set on the command line
@@ -608,10 +610,8 @@ class SetImage(command.Command):
         image_client = self.app.client_manager.image
 
         if getattr(parsed_args, 'owner', None) is not None:
-            self.log.warning(_(
-                'The --owner option is deprecated, '
-                'please use --project instead.'
-            ))
+            LOG.warning(_('The --owner option is deprecated, '
+                          'please use --project instead.'))
 
         kwargs = {}
         copy_attrs = ('name', 'owner', 'min_disk', 'min_ram', 'properties',
@@ -684,16 +684,15 @@ class SetImage(command.Command):
                             # will do a chunked transfer
                             kwargs["data"] = sys.stdin
                         else:
-                            self.log.warning(_('Use --stdin to enable read '
-                                               'image data from standard '
-                                               'input'))
+                            LOG.warning(_('Use --stdin to enable read image '
+                                          'data from standard input'))
 
             if image.properties and parsed_args.properties:
                 image.properties.update(kwargs['properties'])
                 kwargs['properties'] = image.properties
 
             if not kwargs:
-                self.log.warning('no arguments specified')
+                LOG.warning(_('no arguments specified'))
                 return
 
             image = image_client.images.update(image.id, **kwargs)
diff --git a/openstackclient/image/v2/image.py b/openstackclient/image/v2/image.py
index 53f9530b96..82566ff379 100644
--- a/openstackclient/image/v2/image.py
+++ b/openstackclient/image/v2/image.py
@@ -16,6 +16,7 @@
 """Image V2 Action Implementations"""
 
 import argparse
+import logging
 
 from glanceclient.common import utils as gc_utils
 from osc_lib.cli import parseractions
@@ -33,6 +34,9 @@ DEFAULT_CONTAINER_FORMAT = 'bare'
 DEFAULT_DISK_FORMAT = 'raw'
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _format_image(image):
     """Format an image to make it more consistent with OSC operations. """
 
@@ -280,10 +284,8 @@ class CreateImage(command.ShowOne):
         project_arg = parsed_args.project
         if parsed_args.owner:
             project_arg = parsed_args.owner
-            self.log.warning(_(
-                'The --owner option is deprecated, '
-                'please use --project instead.'
-            ))
+            LOG.warning(_('The --owner option is deprecated, '
+                          'please use --project instead.'))
         if project_arg:
             kwargs['owner'] = common.find_project(
                 identity_client,
@@ -301,7 +303,7 @@ class CreateImage(command.ShowOne):
                                             "the same time"))
 
         if fp is None and parsed_args.file:
-            self.log.warning(_("Failed to get an image file."))
+            LOG.warning(_("Failed to get an image file."))
             return {}, {}
 
         if parsed_args.owner:
@@ -384,9 +386,9 @@ class DeleteImage(command.Command):
                 image_client.images.delete(image_obj.id)
             except Exception as e:
                 del_result += 1
-                self.app.log.error(_("Failed to delete image with "
-                                   "name or ID '%(image)s': %(e)s")
-                                   % {'image': image, 'e': e})
+                LOG.error(_("Failed to delete image with name or "
+                            "ID '%(image)s': %(e)s"),
+                          {'image': image, 'e': e})
 
         total = len(parsed_args.images)
         if (del_result > 0):
@@ -806,10 +808,8 @@ class SetImage(command.Command):
         project_arg = parsed_args.project
         if parsed_args.owner:
             project_arg = parsed_args.owner
-            self.log.warning(_(
-                'The --owner option is deprecated, '
-                'please use --project instead.'
-            ))
+            LOG.warning(_('The --owner option is deprecated, '
+                          'please use --project instead.'))
         if project_arg:
             kwargs['owner'] = common.find_project(
                 identity_client,
@@ -908,8 +908,8 @@ class UnsetImage(command.Command):
                 try:
                     image_client.image_tags.delete(image.id, k)
                 except Exception:
-                    self.log.error(_("tag unset failed,"
-                                   " '%s' is a nonexistent tag ") % k)
+                    LOG.error(_("tag unset failed, '%s' is a "
+                                "nonexistent tag "), k)
                     tagret += 1
 
         if parsed_args.properties:
@@ -917,8 +917,8 @@ class UnsetImage(command.Command):
                 try:
                     assert(k in image.keys())
                 except AssertionError:
-                    self.log.error(_("property unset failed,"
-                                   " '%s' is a nonexistent property ") % k)
+                    LOG.error(_("property unset failed, '%s' is a "
+                                "nonexistent property "), k)
                     propret += 1
             image_client.images.update(
                 image.id,
diff --git a/openstackclient/network/common.py b/openstackclient/network/common.py
index 16cc7379ba..f62840fc04 100644
--- a/openstackclient/network/common.py
+++ b/openstackclient/network/common.py
@@ -12,6 +12,7 @@
 #
 
 import abc
+import logging
 
 from osc_lib.command import command
 from osc_lib import exceptions
@@ -20,6 +21,9 @@ import six
 from openstackclient.i18n import _
 
 
+LOG = logging.getLogger(__name__)
+
+
 @six.add_metaclass(abc.ABCMeta)
 class NetworkAndComputeCommand(command.Command):
     """Network and Compute Command
@@ -39,10 +43,10 @@ class NetworkAndComputeCommand(command.Command):
                                             parsed_args)
 
     def get_parser(self, prog_name):
-        self.log.debug('get_parser(%s)', prog_name)
+        LOG.debug('get_parser(%s)', prog_name)
         parser = super(NetworkAndComputeCommand, self).get_parser(prog_name)
         parser = self.update_parser_common(parser)
-        self.log.debug('common parser: %s', parser)
+        LOG.debug('common parser: %s', parser)
         if self.app.client_manager.is_network_endpoint_enabled():
             return self.update_parser_network(parser)
         else:
@@ -102,7 +106,7 @@ class NetworkAndComputeDelete(NetworkAndComputeCommand):
                             "name_or_id": r,
                             "e": e,
                 }
-                self.app.log.error(msg)
+                LOG.error(msg)
                 ret += 1
 
         if ret:
@@ -134,10 +138,10 @@ class NetworkAndComputeLister(command.Lister):
                                             parsed_args)
 
     def get_parser(self, prog_name):
-        self.log.debug('get_parser(%s)', prog_name)
+        LOG.debug('get_parser(%s)', prog_name)
         parser = super(NetworkAndComputeLister, self).get_parser(prog_name)
         parser = self.update_parser_common(parser)
-        self.log.debug('common parser: %s', parser)
+        LOG.debug('common parser: %s', parser)
         if self.app.client_manager.is_network_endpoint_enabled():
             return self.update_parser_network(parser)
         else:
@@ -185,10 +189,10 @@ class NetworkAndComputeShowOne(command.ShowOne):
                                             parsed_args)
 
     def get_parser(self, prog_name):
-        self.log.debug('get_parser(%s)', prog_name)
+        LOG.debug('get_parser(%s)', prog_name)
         parser = super(NetworkAndComputeShowOne, self).get_parser(prog_name)
         parser = self.update_parser_common(parser)
-        self.log.debug('common parser: %s', parser)
+        LOG.debug('common parser: %s', parser)
         if self.app.client_manager.is_network_endpoint_enabled():
             return self.update_parser_network(parser)
         else:
diff --git a/openstackclient/network/v2/address_scope.py b/openstackclient/network/v2/address_scope.py
index bc1a96c326..6cd13f8ce7 100644
--- a/openstackclient/network/v2/address_scope.py
+++ b/openstackclient/network/v2/address_scope.py
@@ -13,6 +13,8 @@
 
 """Address scope action implementations"""
 
+import logging
+
 from osc_lib.command import command
 from osc_lib import exceptions
 from osc_lib import utils
@@ -21,6 +23,9 @@ from openstackclient.i18n import _
 from openstackclient.identity import common as identity_common
 
 
+LOG = logging.getLogger(__name__)
+
+
 def _get_columns(item):
     columns = list(item.keys())
     if 'tenant_id' in columns:
@@ -122,9 +127,9 @@ class DeleteAddressScope(command.Command):
                 client.delete_address_scope(obj)
             except Exception as e:
                 result += 1
-                self.app.log.error(_("Failed to delete address scope with "
-                                   "name or ID '%(scope)s': %(e)s")
-                                   % {'scope': scope, 'e': e})
+                LOG.error(_("Failed to delete address scope with "
+                            "name or ID '%(scope)s': %(e)s"),
+                          {'scope': scope, 'e': e})
 
         if result > 0:
             total = len(parsed_args.address_scope)
diff --git a/openstackclient/network/v2/port.py b/openstackclient/network/v2/port.py
index 1c5db706e3..57461f8949 100644
--- a/openstackclient/network/v2/port.py
+++ b/openstackclient/network/v2/port.py
@@ -293,9 +293,9 @@ class DeletePort(command.Command):
                 client.delete_port(obj)
             except Exception as e:
                 result += 1
-                self.app.log.error(_("Failed to delete port with "
-                                   "name or ID '%(port)s': %(e)s")
-                                   % {'port': port, 'e': e})
+                LOG.error(_("Failed to delete port with "
+                            "name or ID '%(port)s': %(e)s"),
+                          {'port': port, 'e': e})
 
         if result > 0:
             total = len(parsed_args.port)
diff --git a/openstackclient/tests/compute/v2/test_service.py b/openstackclient/tests/compute/v2/test_service.py
index b360c9dce4..3afe964f72 100644
--- a/openstackclient/tests/compute/v2/test_service.py
+++ b/openstackclient/tests/compute/v2/test_service.py
@@ -330,12 +330,9 @@ class TestServiceSet(TestService):
         ]
         parsed_args = self.check_parser(self.cmd, arglist, verifylist)
 
-        with mock.patch.object(self.cmd.log, 'error') as mock_log:
-            with mock.patch.object(self.service_mock, 'enable',
-                                   side_effect=Exception()):
-                self.assertRaises(exceptions.CommandError,
-                                  self.cmd.take_action, parsed_args)
-                mock_log.assert_called_once_with(
-                    "Failed to set service status to %s", "enabled")
-                self.service_mock.force_down.assert_called_once_with(
-                    self.service.host, self.service.binary, force_down=True)
+        with mock.patch.object(self.service_mock, 'enable',
+                               side_effect=Exception()):
+            self.assertRaises(exceptions.CommandError,
+                              self.cmd.take_action, parsed_args)
+            self.service_mock.force_down.assert_called_once_with(
+                self.service.host, self.service.binary, force_down=True)