From 4363af6cc81e4bc63fb39fae7b059ca3defaabe0 Mon Sep 17 00:00:00 2001 From: Brian Waldon <bcwaldon@gmail.com> Date: Wed, 20 Jun 2012 10:33:43 -0700 Subject: [PATCH] Standardize logger instantiation Use LOG for variable name and __name__ for logger name. Also document this fact in HACKING.rst Fixes bug 1015685 Change-Id: I0d9d80bef66197a28ed3d650f17859202048d776 --- HACKING.rst | 8 ++ glance/api/cached_images.py | 4 - glance/api/middleware/cache.py | 10 +-- glance/api/middleware/cache_manage.py | 4 +- glance/api/middleware/version_negotiation.py | 14 ++-- glance/api/policy.py | 4 +- glance/api/v1/controller.py | 8 +- glance/api/v1/images.py | 74 +++++++++---------- glance/api/v1/members.py | 26 +++---- glance/api/v1/router.py | 4 - glance/api/v2/router.py | 4 - glance/client.py | 2 - glance/common/auth.py | 4 +- glance/common/utils.py | 4 +- glance/db/sqlalchemy/api.py | 18 ++--- glance/db/sqlalchemy/migrate_repo/schema.py | 6 +- .../versions/015_quote_swift_credentials.py | 8 +- glance/db/sqlalchemy/migration.py | 10 +-- glance/image_cache/__init__.py | 46 ++++++------ glance/image_cache/drivers/base.py | 4 +- glance/image_cache/drivers/sqlite.py | 38 +++++----- glance/image_cache/drivers/xattr.py | 46 ++++++------ glance/image_cache/prefetcher.py | 20 ++--- glance/image_cache/pruner.py | 4 - glance/notifier/notify_kombu.py | 30 ++++---- glance/notifier/notify_log.py | 2 +- glance/notifier/notify_qpid.py | 4 +- glance/registry/__init__.py | 12 +-- glance/registry/api/v1/images.py | 22 +++--- glance/registry/api/v1/members.py | 10 +-- glance/store/__init__.py | 12 +-- glance/store/base.py | 6 +- glance/store/filesystem.py | 18 ++--- glance/store/http.py | 6 +- glance/store/location.py | 6 +- glance/store/rbd.py | 10 +-- glance/store/s3.py | 28 +++---- glance/store/scrubber.py | 32 ++++---- glance/store/swift.py | 45 ++++++----- glance/tests/unit/test_notifier.py | 2 +- glance/tests/unit/v1/test_api.py | 2 +- tools/migrate_image_owners.py | 16 ++-- 42 files changed, 311 insertions(+), 322 deletions(-) diff --git a/HACKING.rst b/HACKING.rst index 42e36a3139..f0cdf86d9e 100644 --- a/HACKING.rst +++ b/HACKING.rst @@ -199,3 +199,11 @@ with the help of openstack-common's update.py script. See: The copy of the code should never be directly modified here. Please always update openstack-common first and then run the script to copy the changes across. + + +Logging +------- +Use __name__ as the name of your logger and name your module-level logger +objects 'LOG':: + + LOG = logging.getLogger(__name__) diff --git a/glance/api/cached_images.py b/glance/api/cached_images.py index 05e8700f5a..b3c4554e02 100644 --- a/glance/api/cached_images.py +++ b/glance/api/cached_images.py @@ -19,8 +19,6 @@ Controller for Image Cache Management API """ -import logging - import webob.exc from glance.api import policy @@ -29,8 +27,6 @@ from glance.common import exception from glance.common import wsgi from glance import image_cache -logger = logging.getLogger(__name__) - class Controller(controller.BaseController): """ diff --git a/glance/api/middleware/cache.py b/glance/api/middleware/cache.py index d52f51d97f..1c0a4839d2 100644 --- a/glance/api/middleware/cache.py +++ b/glance/api/middleware/cache.py @@ -37,7 +37,7 @@ from glance.common import wsgi from glance import image_cache from glance import registry -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) get_images_re = re.compile(r'^(/v\d+)*/images/([^\/]+)$') @@ -46,7 +46,7 @@ class CacheFilter(wsgi.Middleware): def __init__(self, app): self.cache = image_cache.ImageCache() self.serializer = images.ImageSerializer() - logger.info(_("Initialized image cache middleware")) + LOG.info(_("Initialized image cache middleware")) super(CacheFilter, self).__init__(app) def process_request(self, request): @@ -73,7 +73,7 @@ class CacheFilter(wsgi.Middleware): return None if self.cache.is_cached(image_id): - logger.debug(_("Cache hit for image '%s'"), image_id) + LOG.debug(_("Cache hit for image '%s'"), image_id) image_iterator = self.get_from_cache(image_id) context = request.context try: @@ -92,7 +92,7 @@ class CacheFilter(wsgi.Middleware): msg = _("Image cache contained image file for image '%s', " "however the registry did not contain metadata for " "that image!" % image_id) - logger.error(msg) + LOG.error(msg) return None def process_response(self, resp): @@ -117,7 +117,7 @@ class CacheFilter(wsgi.Middleware): if self.cache.is_cached(image_id): if request.method == 'DELETE': - logger.info(_("Removing image %s from cache"), image_id) + LOG.info(_("Removing image %s from cache"), image_id) self.cache.delete_cached_image(image_id) return resp diff --git a/glance/api/middleware/cache_manage.py b/glance/api/middleware/cache_manage.py index 4210a4d7f0..f8410a1385 100644 --- a/glance/api/middleware/cache_manage.py +++ b/glance/api/middleware/cache_manage.py @@ -26,7 +26,7 @@ import routes from glance.api import cached_images from glance.common import wsgi -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) class CacheManageFilter(wsgi.Middleware): @@ -72,7 +72,7 @@ class CacheManageFilter(wsgi.Middleware): self._mapper = mapper self._resource = resource - logger.info(_("Initialized image cache management middleware")) + LOG.info(_("Initialized image cache management middleware")) super(CacheManageFilter, self).__init__(app) def process_request(self, request): diff --git a/glance/api/middleware/version_negotiation.py b/glance/api/middleware/version_negotiation.py index d3d3e10b19..150f890b22 100644 --- a/glance/api/middleware/version_negotiation.py +++ b/glance/api/middleware/version_negotiation.py @@ -26,7 +26,7 @@ import logging from glance.api import versions from glance.common import wsgi -logger = logging.getLogger('glance.api.middleware.version_negotiation') +LOG = logging.getLogger(__name__) class VersionNegotiationFilter(wsgi.Middleware): @@ -40,7 +40,7 @@ class VersionNegotiationFilter(wsgi.Middleware): msg = _("Determining version of request: %(method)s %(path)s" " Accept: %(accept)s") args = {'method': req.method, 'path': req.path, 'accept': req.accept} - logger.debug(msg % args) + LOG.debug(msg % args) # If the request is for /versions, just return the versions container #TODO(bcwaldon): deprecate this behavior @@ -49,24 +49,24 @@ class VersionNegotiationFilter(wsgi.Middleware): accept = str(req.accept) if accept.startswith('application/vnd.openstack.images-'): - logger.debug(_("Using media-type versioning")) + LOG.debug(_("Using media-type versioning")) token_loc = len('application/vnd.openstack.images-') req_version = accept[token_loc:] else: - logger.debug(_("Using url versioning")) + LOG.debug(_("Using url versioning")) # Remove version in url so it doesn't conflict later req_version = req.path_info_pop() try: version = self._match_version_string(req_version) except ValueError: - logger.debug(_("Unknown version. Returning version choices.")) + LOG.debug(_("Unknown version. Returning version choices.")) return self.versions_app req.environ['api.version'] = version req.path_info = ''.join(('/v', str(version), req.path_info)) - logger.debug(_("Matched version: v%d"), version) - logger.debug('new uri %s' % req.path_info) + LOG.debug(_("Matched version: v%d"), version) + LOG.debug('new uri %s' % req.path_info) return None def _match_version_string(self, subject): diff --git a/glance/api/policy.py b/glance/api/policy.py index bfaf68cdd4..facd228e23 100644 --- a/glance/api/policy.py +++ b/glance/api/policy.py @@ -25,7 +25,7 @@ from glance.common import exception from glance.openstack.common import cfg from glance.openstack.common import policy -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) policy_opts = ( cfg.StrOpt('policy_file', default=None), @@ -74,7 +74,7 @@ class Enforcer(object): """ mtime = os.path.getmtime(self.policy_path) if not self.policy_file_contents or mtime != self.policy_file_mtime: - logger.debug(_("Loading policy from %s") % self.policy_path) + LOG.debug(_("Loading policy from %s") % self.policy_path) with open(self.policy_path) as fap: raw_contents = fap.read() self.policy_file_contents = json.loads(raw_contents) diff --git a/glance/api/v1/controller.py b/glance/api/v1/controller.py index d4417801a1..662dd7154b 100644 --- a/glance/api/v1/controller.py +++ b/glance/api/v1/controller.py @@ -22,7 +22,7 @@ import webob.exc from glance import registry from glance.common import exception -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) class BaseController(object): @@ -41,12 +41,12 @@ class BaseController(object): return registry.get_image_metadata(context, image_id) except exception.NotFound: msg = _("Image with identifier %s not found") % image_id - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound( msg, request=request, content_type='text/plain') except exception.Forbidden: msg = _("Forbidden image access") - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPForbidden(msg, request=request, content_type='text/plain') @@ -58,7 +58,7 @@ class BaseController(object): image = self.get_image_meta_or_404(request, image_id) if image['status'] != 'active': msg = _("Image %s is not active") % image_id - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound( msg, request=request, content_type='text/plain') return image diff --git a/glance/api/v1/images.py b/glance/api/v1/images.py index 61b0e85714..f83c3bda33 100644 --- a/glance/api/v1/images.py +++ b/glance/api/v1/images.py @@ -51,7 +51,7 @@ from glance import registry from glance import notifier -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) SUPPORTED_PARAMS = glance.api.v1.SUPPORTED_PARAMS SUPPORTED_FILTERS = glance.api.v1.SUPPORTED_FILTERS @@ -236,7 +236,7 @@ class Controller(controller.BaseController): if source.lower().startswith(scheme): return source msg = _("External sourcing not supported for store %s") % source - logger.error(msg) + LOG.error(msg) raise HTTPBadRequest(explanation=msg, request=req, content_type="text/plain") @@ -317,20 +317,20 @@ class Controller(controller.BaseController): except exception.Duplicate: msg = (_("An image with identifier %s already exists") % image_meta['id']) - logger.error(msg) + LOG.error(msg) raise HTTPConflict(explanation=msg, request=req, content_type="text/plain") except exception.Invalid, e: msg = (_("Failed to reserve image. Got error: %(e)s") % locals()) for line in msg.split('\n'): - logger.error(line) + LOG.error(line) raise HTTPBadRequest(explanation=msg, request=req, content_type="text/plain") except exception.Forbidden: msg = _("Forbidden to reserve image.") - logger.error(msg) + LOG.error(msg) raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain") @@ -359,7 +359,7 @@ class Controller(controller.BaseController): except exception.InvalidContentType: self._safe_kill(req, image_meta['id']) msg = _("Content-Type must be application/octet-stream") - logger.error(msg) + LOG.error(msg) raise HTTPBadRequest(explanation=msg) image_data = req.body_file @@ -369,8 +369,8 @@ class Controller(controller.BaseController): elif 'x-image-meta-size' in req.headers: image_size = int(req.headers['x-image-meta-size']) else: - logger.debug(_("Got request with no content-length and no " - "x-image-meta-size header")) + LOG.debug(_("Got request with no content-length and no " + "x-image-meta-size header")) image_size = 0 scheme = req.headers.get('x-image-meta-store', CONF.default_store) @@ -378,19 +378,19 @@ class Controller(controller.BaseController): store = self.get_store_or_400(req, scheme) image_id = image_meta['id'] - logger.debug(_("Setting image %s to status 'saving'"), image_id) + LOG.debug(_("Setting image %s to status 'saving'"), image_id) registry.update_image_metadata(req.context, image_id, {'status': 'saving'}) try: - logger.debug(_("Uploading image data for image %(image_id)s " - "to %(scheme)s store"), locals()) + LOG.debug(_("Uploading image data for image %(image_id)s " + "to %(scheme)s store"), locals()) if image_size > IMAGE_SIZE_CAP: max_image_size = IMAGE_SIZE_CAP msg = _("Denying attempt to upload image larger than " "%(max_image_size)d. Supplied image size was " "%(image_size)d") % locals() - logger.warn(msg) + LOG.warn(msg) raise HTTPBadRequest(explanation=msg, request=req) location, size, checksum = store.add(image_meta['id'], @@ -405,7 +405,7 @@ class Controller(controller.BaseController): "checksum generated from uploaded image " "(%(checksum)s) did not match. Setting image " "status to 'killed'.") % locals() - logger.error(msg) + LOG.error(msg) self._safe_kill(req, image_id) raise HTTPBadRequest(explanation=msg, content_type="text/plain", @@ -413,9 +413,9 @@ class Controller(controller.BaseController): # Update the database with the checksum returned # from the backend store - logger.debug(_("Updating image %(image_id)s data. " - "Checksum set to %(checksum)s, size set " - "to %(size)d"), locals()) + LOG.debug(_("Updating image %(image_id)s data. " + "Checksum set to %(checksum)s, size set " + "to %(size)d"), locals()) registry.update_image_metadata(req.context, image_id, {'checksum': checksum, 'size': size}) @@ -425,14 +425,14 @@ class Controller(controller.BaseController): except exception.Duplicate, e: msg = _("Attempt to upload duplicate image: %s") % e - logger.error(msg) + LOG.error(msg) self._safe_kill(req, image_id) self.notifier.error('image.upload', msg) raise HTTPConflict(explanation=msg, request=req) except exception.Forbidden, e: msg = _("Forbidden upload attempt: %s") % e - logger.error(msg) + LOG.error(msg) self._safe_kill(req, image_id) self.notifier.error('image.upload', msg) raise HTTPForbidden(explanation=msg, @@ -441,7 +441,7 @@ class Controller(controller.BaseController): except exception.StorageFull, e: msg = _("Image storage media is full: %s") % e - logger.error(msg) + LOG.error(msg) self._safe_kill(req, image_id) self.notifier.error('image.upload', msg) raise HTTPRequestEntityTooLarge(explanation=msg, request=req, @@ -449,7 +449,7 @@ class Controller(controller.BaseController): except exception.StorageWriteDenied, e: msg = _("Insufficient permissions on image storage media: %s") % e - logger.error(msg) + LOG.error(msg) self._safe_kill(req, image_id) self.notifier.error('image.upload', msg) raise HTTPServiceUnavailable(explanation=msg, request=req, @@ -462,7 +462,7 @@ class Controller(controller.BaseController): except Exception, e: tb_info = traceback.format_exc() - logger.error(tb_info) + LOG.error(tb_info) self._safe_kill(req, image_id) @@ -494,7 +494,7 @@ class Controller(controller.BaseController): msg = (_("Failed to activate image. Got error: %(e)s") % locals()) for line in msg.split('\n'): - logger.error(line) + LOG.error(line) self.notifier.error('image.update', msg) raise HTTPBadRequest(explanation=msg, request=req, @@ -523,9 +523,9 @@ class Controller(controller.BaseController): try: self._kill(req, image_id) except Exception, e: - logger.error(_("Unable to kill image %(id)s: " - "%(exc)s") % ({'id': image_id, - 'exc': repr(e)})) + LOG.error(_("Unable to kill image %(id)s: " + "%(exc)s") % ({'id': image_id, + 'exc': repr(e)})) def _upload_and_activate(self, req, image_meta): """ @@ -680,7 +680,7 @@ class Controller(controller.BaseController): msg = (_("Failed to update image metadata. Got error: %(e)s") % locals()) for line in msg.split('\n'): - logger.error(line) + LOG.error(line) self.notifier.error('image.update', msg) raise HTTPBadRequest(explanation=msg, request=req, @@ -688,7 +688,7 @@ class Controller(controller.BaseController): except exception.NotFound, e: msg = ("Failed to find image to update: %(e)s" % locals()) for line in msg.split('\n'): - logger.info(line) + LOG.info(line) self.notifier.info('image.update', msg) raise HTTPNotFound(explanation=msg, request=req, @@ -696,7 +696,7 @@ class Controller(controller.BaseController): except exception.Forbidden, e: msg = ("Forbidden to update image: %(e)s" % locals()) for line in msg.split('\n'): - logger.info(line) + LOG.info(line) self.notifier.info('image.update', msg) raise HTTPForbidden(explanation=msg, request=req, @@ -728,7 +728,7 @@ class Controller(controller.BaseController): image = self.get_image_meta_or_404(req, id) if image['protected']: msg = _("Image is protected") - logger.debug(msg) + LOG.debug(msg) raise HTTPForbidden(explanation=msg, request=req, content_type="text/plain") @@ -745,7 +745,7 @@ class Controller(controller.BaseController): except exception.NotFound, e: msg = ("Failed to find image to delete: %(e)s" % locals()) for line in msg.split('\n'): - logger.info(line) + LOG.info(line) self.notifier.info('image.delete', msg) raise HTTPNotFound(explanation=msg, request=req, @@ -753,7 +753,7 @@ class Controller(controller.BaseController): except exception.Forbidden, e: msg = ("Forbidden to delete image: %(e)s" % locals()) for line in msg.split('\n'): - logger.info(line) + LOG.info(line) self.notifier.info('image.delete', msg) raise HTTPForbidden(explanation=msg, request=req, @@ -775,7 +775,7 @@ class Controller(controller.BaseController): return get_store_from_scheme(scheme) except exception.UnknownScheme: msg = _("Store for scheme %s not found") - logger.error(msg % scheme) + LOG.error(msg % scheme) raise HTTPBadRequest(explanation=msg, request=request, content_type='text/plain') @@ -791,7 +791,7 @@ class Controller(controller.BaseController): get_store_from_scheme(scheme) except exception.UnknownScheme: msg = _("Store for scheme %s not found") - logger.error(msg % scheme) + LOG.error(msg % scheme) # message on stderr will only be visible if started directly via # bin/glance-api, as opposed to being daemonized by glance-control sys.stderr.write(msg % scheme) @@ -819,7 +819,7 @@ class ImageDeserializer(wsgi.JSONRequestDeserializer): msg = _("Denying attempt to upload image larger than " "%(max_image_size)d. Supplied image size was " "%(incoming_image_size)d") % locals() - logger.warn(msg) + LOG.warn(msg) raise HTTPBadRequest(explanation=msg, request=request) data = request.body_file if self.has_body(request) else None @@ -894,7 +894,7 @@ class ImageSerializer(wsgi.JSONResponseSerializer): except Exception, err: msg = _("An error occurred during image.send" " notification: %(err)s") % locals() - logger.error(msg) + LOG.error(msg) def show(self, response, result): image_meta = result['image_meta'] @@ -925,14 +925,14 @@ class ImageSerializer(wsgi.JSONResponseSerializer): except Exception, err: msg = _("An error occurred reading from backend storage " "for image %(image_id)s: %(err)s") % locals() - logger.error(msg) + LOG.error(msg) raise if expected_size != bytes_written: msg = _("Backend storage for image %(image_id)s " "disconnected after writing only %(bytes_written)d " "bytes") % locals() - logger.error(msg) + LOG.error(msg) raise IOError(errno.EPIPE, _("Corrupt image download for " "image %(image_id)s") % locals()) diff --git a/glance/api/v1/members.py b/glance/api/v1/members.py index bd0c7662eb..0c3fcc6dc1 100644 --- a/glance/api/v1/members.py +++ b/glance/api/v1/members.py @@ -25,7 +25,7 @@ from glance.common import wsgi from glance import registry -logger = logging.getLogger('glance.api.v1.members') +LOG = logging.getLogger(__name__) class Controller(object): @@ -48,11 +48,11 @@ class Controller(object): members = registry.get_image_members(req.context, image_id) except exception.NotFound: msg = _("Image with identifier %s not found") % image_id - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) except exception.Forbidden: msg = _("Unauthorized image access") - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPForbidden(msg) return dict(members=members) @@ -68,11 +68,11 @@ class Controller(object): registry.delete_member(req.context, image_id, id) except exception.NotFound, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) except exception.Forbidden, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) return webob.exc.HTTPNoContent() @@ -106,15 +106,15 @@ class Controller(object): registry.add_member(req.context, image_id, id, can_share) except exception.Invalid, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPBadRequest(explanation=msg) except exception.NotFound, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) except exception.Forbidden, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) return webob.exc.HTTPNoContent() @@ -137,15 +137,15 @@ class Controller(object): registry.replace_members(req.context, image_id, body) except exception.Invalid, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPBadRequest(explanation=msg) except exception.NotFound, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) except exception.Forbidden, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) return webob.exc.HTTPNoContent() @@ -167,11 +167,11 @@ class Controller(object): members = registry.get_member_images(req.context, id) except exception.NotFound, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPNotFound(msg) except exception.Forbidden, e: msg = "%s" % e - logger.debug(msg) + LOG.debug(msg) raise webob.exc.HTTPForbidden(msg) return dict(shared_images=members) diff --git a/glance/api/v1/router.py b/glance/api/v1/router.py index 0ee7929568..4bdd85835a 100644 --- a/glance/api/v1/router.py +++ b/glance/api/v1/router.py @@ -15,16 +15,12 @@ # License for the specific language governing permissions and limitations # under the License. -import logging - import routes from glance.api.v1 import images from glance.api.v1 import members from glance.common import wsgi -logger = logging.getLogger(__name__) - class API(wsgi.Router): diff --git a/glance/api/v2/router.py b/glance/api/v2/router.py index eec9c6346f..0774272b6c 100644 --- a/glance/api/v2/router.py +++ b/glance/api/v2/router.py @@ -15,8 +15,6 @@ # License for the specific language governing permissions and limitations # under the License. -import logging - from glance.api.v2 import image_access from glance.api.v2 import image_data from glance.api.v2 import image_tags @@ -25,8 +23,6 @@ from glance.api.v2 import root from glance.api.v2 import schemas from glance.common import wsgi -logger = logging.getLogger(__name__) - class API(wsgi.Router): diff --git a/glance/client.py b/glance/client.py index d49a152457..cbfabe9ead 100644 --- a/glance/client.py +++ b/glance/client.py @@ -22,7 +22,6 @@ Client classes for callers of a Glance system import errno import httplib import json -import logging import os import socket import sys @@ -33,7 +32,6 @@ from glance.common import client as base_client from glance.common import exception from glance.common import utils -logger = logging.getLogger(__name__) SUPPORTED_PARAMS = glance.api.v1.SUPPORTED_PARAMS SUPPORTED_FILTERS = glance.api.v1.SUPPORTED_FILTERS diff --git a/glance/common/auth.py b/glance/common/auth.py index b97a993c3d..21d3bdd857 100644 --- a/glance/common/auth.py +++ b/glance/common/auth.py @@ -39,7 +39,7 @@ import httplib2 from glance.common import exception -logger = logging.getLogger('glance.common.auth') +LOG = logging.getLogger(__name__) class BaseStrategy(object): @@ -204,7 +204,7 @@ class KeystoneStrategy(BaseStrategy): service_type = service['type'] except KeyError: msg = _('Encountered service with no "type": %s' % service) - logger.warn(msg) + LOG.warn(msg) continue if service_type == 'image': diff --git a/glance/common/utils.py b/glance/common/utils.py index d70fc43fb3..ce0454d188 100644 --- a/glance/common/utils.py +++ b/glance/common/utils.py @@ -35,7 +35,7 @@ from webob import exc from glance.common import exception -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) def chunkreadable(iter, chunk_size=65536): @@ -309,7 +309,7 @@ def mutating(func): def wrapped(self, req, *args, **kwargs): if req.context.read_only: msg = _("Read-only access") - logger.debug(msg) + LOG.debug(msg) raise exc.HTTPForbidden(msg, request=req, content_type="text/plain") return func(self, req, *args, **kwargs) diff --git a/glance/db/sqlalchemy/api.py b/glance/db/sqlalchemy/api.py index f02a236363..5ac287d036 100644 --- a/glance/db/sqlalchemy/api.py +++ b/glance/db/sqlalchemy/api.py @@ -48,7 +48,7 @@ _MAX_RETRIES = None _RETRY_INTERVAL = None BASE = models.BASE sa_logger = None -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) CONTAINER_FORMATS = ['ami', 'ari', 'aki', 'bare', 'ovf'] @@ -83,7 +83,7 @@ class MySQLPingListener(object): dbapi_con.cursor().execute('select 1') except dbapi_con.OperationalError, ex: if ex.args[0] in (2006, 2013, 2014, 2045, 2055): - logger.warn('Got mysql server has gone away: %s', ex) + LOG.warn('Got mysql server has gone away: %s', ex) raise DisconnectionError("Database server went away") else: raise @@ -94,7 +94,7 @@ def configure_db(): Establish the database, create an engine if needed, and register the models. """ - global _ENGINE, sa_logger, logger, _MAX_RETRIES, _RETRY_INTERVAL + global _ENGINE, sa_logger, LOG, _MAX_RETRIES, _RETRY_INTERVAL if not _ENGINE: sql_connection = CONF.sql_connection _MAX_RETRIES = CONF.sql_max_retries @@ -115,7 +115,7 @@ def configure_db(): msg = _("Error configuring registry database with supplied " "sql_connection '%(sql_connection)s'. " "Got error:\n%(err)s") % locals() - logger.error(msg) + LOG.error(msg) raise sa_logger = logging.getLogger('sqlalchemy.engine') @@ -123,7 +123,7 @@ def configure_db(): sa_logger.setLevel(logging.DEBUG) if CONF.db_auto_create: - logger.info('auto-creating glance registry DB') + LOG.info('auto-creating glance registry DB') models.register_models(_ENGINE) try: migration.version_control() @@ -131,12 +131,12 @@ def configure_db(): # only arises when the DB exists and is under version control pass else: - logger.info('not auto-creating glance registry DB') + LOG.info('not auto-creating glance registry DB') def check_mutate_authorization(context, image_ref): if not is_image_mutable(context, image_ref): - logger.info(_("Attempted to modify image user did not own.")) + LOG.info(_("Attempted to modify image user did not own.")) msg = _("You do not own this image") if image_ref.is_public: exc_class = exception.ForbiddenPublicImage @@ -181,7 +181,7 @@ def wrap_db_error(f): global _RETRY_INTERVAL remaining_attempts = _MAX_RETRIES while True: - logger.warning(_('SQL connection failed. %d attempts left.'), + LOG.warning(_('SQL connection failed. %d attempts left.'), remaining_attempts) remaining_attempts -= 1 time.sleep(_RETRY_INTERVAL) @@ -369,7 +369,7 @@ def paginate_query(query, model, limit, sort_keys, marker=None, if 'id' not in sort_keys: # TODO(justinsb): If this ever gives a false-positive, check # the actual primary key, rather than assuming its id - logger.warn(_('Id not in sort_keys; is sort_keys unique?')) + LOG.warn(_('Id not in sort_keys; is sort_keys unique?')) assert(not (sort_dir and sort_dirs)) diff --git a/glance/db/sqlalchemy/migrate_repo/schema.py b/glance/db/sqlalchemy/migrate_repo/schema.py index f219120edf..87e452875a 100644 --- a/glance/db/sqlalchemy/migrate_repo/schema.py +++ b/glance/db/sqlalchemy/migrate_repo/schema.py @@ -24,7 +24,7 @@ import logging import sqlalchemy.types -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) String = lambda length: sqlalchemy.types.String( @@ -92,11 +92,11 @@ def from_migration_import(module_name, fromlist): def create_tables(tables): for table in tables: - logger.info(_("creating table %(table)s") % locals()) + LOG.info(_("creating table %(table)s") % locals()) table.create() def drop_tables(tables): for table in tables: - logger.info(_("dropping table %(table)s") % locals()) + LOG.info(_("dropping table %(table)s") % locals()) table.drop() diff --git a/glance/db/sqlalchemy/migrate_repo/versions/015_quote_swift_credentials.py b/glance/db/sqlalchemy/migrate_repo/versions/015_quote_swift_credentials.py index 6956fa4a51..c352460590 100644 --- a/glance/db/sqlalchemy/migrate_repo/versions/015_quote_swift_credentials.py +++ b/glance/db/sqlalchemy/migrate_repo/versions/015_quote_swift_credentials.py @@ -24,7 +24,7 @@ import sqlalchemy from glance.common import exception import glance.store.swift -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) def upgrade(migrate_engine): @@ -113,7 +113,7 @@ def legacy_parse_uri(self, uri): "swift+http://user:pass@authurl.com/v1/container/obj" ) - logger.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) + LOG.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlparse(uri) @@ -145,7 +145,7 @@ def legacy_parse_uri(self, uri): if len(cred_parts) == 1: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() elif len(cred_parts) == 3: user = ':'.join(cred_parts[0:2]) @@ -166,5 +166,5 @@ def legacy_parse_uri(self, uri): self.authurl = '/'.join(path_parts) except IndexError: reason = _("Badly formed S3 URI: %s") % uri - logger.error(message=reason) + LOG.error(message=reason) raise exception.BadStoreUri() diff --git a/glance/db/sqlalchemy/migration.py b/glance/db/sqlalchemy/migration.py index a8b6dadfe4..ce4c33f191 100644 --- a/glance/db/sqlalchemy/migration.py +++ b/glance/db/sqlalchemy/migration.py @@ -30,7 +30,7 @@ from migrate.versioning import repository as versioning_repository from glance.common import exception from glance.openstack.common import cfg -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) CONF = cfg.CONF @@ -62,8 +62,8 @@ def upgrade(version=None): repo_path = get_migrate_repo_path() sql_connection = CONF.sql_connection version_str = version or 'latest' - logger.info(_("Upgrading %(sql_connection)s to version %(version_str)s") % - locals()) + LOG.info(_("Upgrading %(sql_connection)s to version %(version_str)s") % + locals()) return versioning_api.upgrade(sql_connection, repo_path, version) @@ -77,8 +77,8 @@ def downgrade(version): db_version() # Ensure db is under migration control repo_path = get_migrate_repo_path() sql_connection = CONF.sql_connection - logger.info(_("Downgrading %(sql_connection)s to version %(version)s") % - locals()) + LOG.info(_("Downgrading %(sql_connection)s to version %(version)s") % + locals()) return versioning_api.downgrade(sql_connection, repo_path, version) diff --git a/glance/image_cache/__init__.py b/glance/image_cache/__init__.py index 0167ed7cfb..6449fa4f67 100644 --- a/glance/image_cache/__init__.py +++ b/glance/image_cache/__init__.py @@ -26,7 +26,7 @@ from glance.common import utils from glance.openstack.common import cfg from glance.openstack.common import importutils -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) image_cache_opts = [ cfg.StrOpt('image_cache_driver', default='sqlite'), @@ -56,15 +56,15 @@ class ImageCache(object): driver_module = (__name__ + '.drivers.' + driver_name + '.Driver') try: self.driver_class = importutils.import_class(driver_module) - logger.info(_("Image cache loaded driver '%s'.") % - driver_name) + LOG.info(_("Image cache loaded driver '%s'.") % + driver_name) except ImportError, import_err: - logger.warn(_("Image cache driver " - "'%(driver_name)s' failed to load. " - "Got error: '%(import_err)s.") % locals()) + LOG.warn(_("Image cache driver " + "'%(driver_name)s' failed to load. " + "Got error: '%(import_err)s.") % locals()) driver_module = __name__ + '.drivers.sqlite.Driver' - logger.info(_("Defaulting to SQLite driver.")) + LOG.info(_("Defaulting to SQLite driver.")) self.driver_class = importutils.import_class(driver_module) self.configure_driver() @@ -78,10 +78,10 @@ class ImageCache(object): self.driver.configure() except exception.BadDriverConfiguration, config_err: driver_module = self.driver_class.__module__ - logger.warn(_("Image cache driver " - "'%(driver_module)s' failed to configure. " - "Got error: '%(config_err)s") % locals()) - logger.info(_("Defaulting to SQLite driver.")) + LOG.warn(_("Image cache driver " + "'%(driver_module)s' failed to configure. " + "Got error: '%(config_err)s") % locals()) + LOG.info(_("Defaulting to SQLite driver.")) default_module = __name__ + '.drivers.sqlite.Driver' self.driver_class = importutils.import_class(default_module) self.driver = self.driver_class() @@ -163,12 +163,12 @@ class ImageCache(object): max_size = CONF.image_cache_max_size current_size = self.driver.get_cache_size() if max_size > current_size: - logger.debug(_("Image cache has free space, skipping prune...")) + LOG.debug(_("Image cache has free space, skipping prune...")) return (0, 0) overage = current_size - max_size - logger.debug(_("Image cache currently %(overage)d bytes over max " - "size. Starting prune to max size of %(max_size)d ") % + LOG.debug(_("Image cache currently %(overage)d bytes over max " + "size. Starting prune to max size of %(max_size)d ") % locals()) total_bytes_pruned = 0 @@ -176,17 +176,17 @@ class ImageCache(object): entry = self.driver.get_least_recently_accessed() while entry and current_size > max_size: image_id, size = entry - logger.debug(_("Pruning '%(image_id)s' to free %(size)d bytes"), - {'image_id': image_id, 'size': size}) + LOG.debug(_("Pruning '%(image_id)s' to free %(size)d bytes"), + {'image_id': image_id, 'size': size}) self.driver.delete_cached_image(image_id) total_bytes_pruned = total_bytes_pruned + size total_files_pruned = total_files_pruned + 1 current_size = current_size - size entry = self.driver.get_least_recently_accessed() - logger.debug(_("Pruning finished pruning. " - "Pruned %(total_files_pruned)d and " - "%(total_bytes_pruned)d.") % locals()) + LOG.debug(_("Pruning finished pruning. " + "Pruned %(total_files_pruned)d and " + "%(total_bytes_pruned)d.") % locals()) return total_files_pruned, total_bytes_pruned def clean(self, stall_time=None): @@ -219,7 +219,7 @@ class ImageCache(object): if not self.driver.is_cacheable(image_id): return image_iter - logger.debug(_("Tee'ing image '%s' into cache"), image_id) + LOG.debug(_("Tee'ing image '%s' into cache"), image_id) def tee_iter(image_id): try: @@ -231,9 +231,9 @@ class ImageCache(object): yield chunk cache_file.flush() except Exception: - logger.exception(_("Exception encountered while tee'ing " - "image '%s' into cache. Continuing " - "with response.") % image_id) + LOG.exception(_("Exception encountered while tee'ing " + "image '%s' into cache. Continuing " + "with response.") % image_id) # NOTE(markwash): continue responding even if caching failed for chunk in image_iter: diff --git a/glance/image_cache/drivers/base.py b/glance/image_cache/drivers/base.py index bef219a3f2..e760d5b722 100644 --- a/glance/image_cache/drivers/base.py +++ b/glance/image_cache/drivers/base.py @@ -26,7 +26,7 @@ from glance.common import exception from glance.common import utils from glance.openstack.common import cfg -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) CONF = cfg.CONF @@ -53,7 +53,7 @@ class Driver(object): self.base_dir = CONF.image_cache_dir if self.base_dir is None: msg = _('Failed to read %s from config') % 'image_cache_dir' - logger.error(msg) + LOG.error(msg) driver = self.__class__.__module__ raise exception.BadDriverConfiguration(driver_name=driver, reason=msg) diff --git a/glance/image_cache/drivers/sqlite.py b/glance/image_cache/drivers/sqlite.py index b7324397e5..e437fc283f 100644 --- a/glance/image_cache/drivers/sqlite.py +++ b/glance/image_cache/drivers/sqlite.py @@ -33,7 +33,7 @@ from glance.common import exception from glance.image_cache.drivers import base from glance.openstack.common import cfg -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) sqlite_opts = [ cfg.StrOpt('image_cache_sqlite_db', default='cache.db'), @@ -119,7 +119,7 @@ class Driver(base.Driver): except sqlite3.DatabaseError, e: msg = _("Failed to initialize the image cache database. " "Got error: %s") % e - logger.error(msg) + LOG.error(msg) raise exception.BadDriverConfiguration(driver_name='sqlite', reason=msg) @@ -156,7 +156,7 @@ class Driver(base.Driver): """ Returns a list of records about cached images. """ - logger.debug(_("Gathering cached image entries.")) + LOG.debug(_("Gathering cached image entries.")) with self.get_db() as db: cur = db.execute("""SELECT image_id, hits, last_accessed, last_modified, size @@ -291,10 +291,10 @@ class Driver(base.Driver): def commit(): with self.get_db() as db: final_path = self.get_image_filepath(image_id) - logger.debug(_("Fetch finished, moving " - "'%(incomplete_path)s' to '%(final_path)s'"), - dict(incomplete_path=incomplete_path, - final_path=final_path)) + LOG.debug(_("Fetch finished, moving " + "'%(incomplete_path)s' to '%(final_path)s'"), + dict(incomplete_path=incomplete_path, + final_path=final_path)) os.rename(incomplete_path, final_path) # Make sure that we "pop" the image from the queue... @@ -315,9 +315,9 @@ class Driver(base.Driver): if os.path.exists(incomplete_path): invalid_path = self.get_image_filepath(image_id, 'invalid') - logger.debug(_("Fetch of cache file failed, rolling back " - "by moving '%(incomplete_path)s' to " - "'%(invalid_path)s'") % locals()) + LOG.debug(_("Fetch of cache file failed, rolling back " + "by moving '%(incomplete_path)s' to " + "'%(invalid_path)s'") % locals()) os.rename(incomplete_path, invalid_path) db.execute("""DELETE FROM cached_images @@ -370,7 +370,7 @@ class Driver(base.Driver): yield conn except sqlite3.DatabaseError, e: msg = _("Error executing SQLite call. Got error: %s") % e - logger.error(msg) + LOG.error(msg) conn.rollback() finally: conn.close() @@ -386,18 +386,18 @@ class Driver(base.Driver): """ if self.is_cached(image_id): msg = _("Not queueing image '%s'. Already cached.") % image_id - logger.warn(msg) + LOG.warn(msg) return False if self.is_being_cached(image_id): msg = _("Not queueing image '%s'. Already being " "written to cache") % image_id - logger.warn(msg) + LOG.warn(msg) return False if self.is_queued(image_id): msg = _("Not queueing image '%s'. Already queued.") % image_id - logger.warn(msg) + LOG.warn(msg) return False path = self.get_image_filepath(image_id, 'queue') @@ -414,7 +414,7 @@ class Driver(base.Driver): """ for path in self.get_cache_files(self.invalid_dir): os.unlink(path) - logger.info("Removed invalid cache file %s", path) + LOG.info("Removed invalid cache file %s", path) def delete_stalled_files(self, older_than): """ @@ -426,7 +426,7 @@ class Driver(base.Driver): """ for path in self.get_cache_files(self.incomplete_dir): os.unlink(path) - logger.info("Removed stalled cache file %s", path) + LOG.info("Removed stalled cache file %s", path) def get_queued_images(self): """ @@ -457,8 +457,8 @@ class Driver(base.Driver): def delete_cached_file(path): if os.path.exists(path): - logger.debug(_("Deleting image cache file '%s'"), path) + LOG.debug(_("Deleting image cache file '%s'"), path) os.unlink(path) else: - logger.warn(_("Cached image file '%s' doesn't exist, unable to" - " delete"), path) + LOG.warn(_("Cached image file '%s' doesn't exist, unable to" + " delete"), path) diff --git a/glance/image_cache/drivers/xattr.py b/glance/image_cache/drivers/xattr.py index 61050f4daf..293f8efe20 100644 --- a/glance/image_cache/drivers/xattr.py +++ b/glance/image_cache/drivers/xattr.py @@ -68,7 +68,7 @@ from glance.common import exception from glance.image_cache.drivers import base from glance.openstack.common import cfg -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) CONF = cfg.CONF @@ -109,7 +109,7 @@ class Driver(base.Driver): "likely you need to edit your fstab and add the " "user_xattr option to the appropriate line for the " "device housing the cache directory.") % locals() - logger.error(msg) + LOG.error(msg) raise exception.BadDriverConfiguration(driver="xattr", reason=msg) else: @@ -143,7 +143,7 @@ class Driver(base.Driver): """ Returns a list of records about cached images. """ - logger.debug(_("Gathering cached image entries.")) + LOG.debug(_("Gathering cached image entries.")) entries = [] for path in get_all_regular_files(self.base_dir): image_id = os.path.basename(path) @@ -273,25 +273,25 @@ class Driver(base.Driver): set_attr('hits', 0) final_path = self.get_image_filepath(image_id) - logger.debug(_("Fetch finished, moving " - "'%(incomplete_path)s' to '%(final_path)s'"), + LOG.debug(_("Fetch finished, moving " + "'%(incomplete_path)s' to '%(final_path)s'"), dict(incomplete_path=incomplete_path, final_path=final_path)) os.rename(incomplete_path, final_path) # Make sure that we "pop" the image from the queue... if self.is_queued(image_id): - logger.debug(_("Removing image '%s' from queue after " - "caching it."), image_id) + LOG.debug(_("Removing image '%s' from queue after " + "caching it."), image_id) os.unlink(self.get_image_filepath(image_id, 'queue')) def rollback(e): set_attr('error', "%s" % e) invalid_path = self.get_image_filepath(image_id, 'invalid') - logger.debug(_("Fetch of cache file failed, rolling back by " - "moving '%(incomplete_path)s' to " - "'%(invalid_path)s'") % locals()) + LOG.debug(_("Fetch of cache file failed, rolling back by " + "moving '%(incomplete_path)s' to " + "'%(invalid_path)s'") % locals()) os.rename(incomplete_path, invalid_path) try: @@ -328,22 +328,22 @@ class Driver(base.Driver): """ if self.is_cached(image_id): msg = _("Not queueing image '%s'. Already cached.") % image_id - logger.warn(msg) + LOG.warn(msg) return False if self.is_being_cached(image_id): msg = _("Not queueing image '%s'. Already being " "written to cache") % image_id - logger.warn(msg) + LOG.warn(msg) return False if self.is_queued(image_id): msg = _("Not queueing image '%s'. Already queued.") % image_id - logger.warn(msg) + LOG.warn(msg) return False path = self.get_image_filepath(image_id, 'queue') - logger.debug(_("Queueing image '%s'."), image_id) + LOG.debug(_("Queueing image '%s'."), image_id) # Touch the file to add it to the queue with open(path, "w") as f: @@ -373,18 +373,18 @@ class Driver(base.Driver): mtime = os.path.getmtime(path) age = now - mtime if not grace: - logger.debug(_("No grace period, reaping '%(path)s'" - " immediately"), locals()) + LOG.debug(_("No grace period, reaping '%(path)s'" + " immediately"), locals()) delete_cached_file(path) reaped += 1 elif age > grace: - logger.debug(_("Cache entry '%(path)s' exceeds grace period, " - "(%(age)i s > %(grace)i s)"), locals()) + LOG.debug(_("Cache entry '%(path)s' exceeds grace period, " + "(%(age)i s > %(grace)i s)"), locals()) delete_cached_file(path) reaped += 1 - logger.info(_("Reaped %(reaped)s %(entry_type)s cache entries"), - locals()) + LOG.info(_("Reaped %(reaped)s %(entry_type)s cache entries"), + locals()) return reaped def reap_invalid(self, grace=None): @@ -427,11 +427,11 @@ def get_all_regular_files(basepath): def delete_cached_file(path): if os.path.exists(path): - logger.debug(_("Deleting image cache file '%s'"), path) + LOG.debug(_("Deleting image cache file '%s'"), path) os.unlink(path) else: - logger.warn(_("Cached image file '%s' doesn't exist, unable to" - " delete"), path) + LOG.warn(_("Cached image file '%s' doesn't exist, unable to" + " delete"), path) def _make_namespaced_xattr_key(key, namespace='user'): diff --git a/glance/image_cache/prefetcher.py b/glance/image_cache/prefetcher.py index dc1b94091c..3098726f86 100644 --- a/glance/image_cache/prefetcher.py +++ b/glance/image_cache/prefetcher.py @@ -36,7 +36,7 @@ import glance.store.swift from glance.store import get_from_backend -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) class Prefetcher(base.CacheApp): @@ -53,16 +53,16 @@ class Prefetcher(base.CacheApp): try: image_meta = registry.get_image_metadata(ctx, image_id) if image_meta['status'] != 'active': - logger.warn(_("Image '%s' is not active. Not caching."), - image_id) + LOG.warn(_("Image '%s' is not active. Not caching."), + image_id) return False except exception.NotFound: - logger.warn(_("No metadata found for image '%s'"), image_id) + LOG.warn(_("No metadata found for image '%s'"), image_id) return False image_data, image_size = get_from_backend(image_meta['location']) - logger.debug(_("Caching image '%s'"), image_id) + LOG.debug(_("Caching image '%s'"), image_id) self.cache.cache_image_iter(image_id, image_data) return True @@ -70,19 +70,19 @@ class Prefetcher(base.CacheApp): images = self.cache.get_queued_images() if not images: - logger.debug(_("Nothing to prefetch.")) + LOG.debug(_("Nothing to prefetch.")) return True num_images = len(images) - logger.debug(_("Found %d images to prefetch"), num_images) + LOG.debug(_("Found %d images to prefetch"), num_images) pool = eventlet.GreenPool(num_images) results = pool.imap(self.fetch_image_into_cache, images) successes = sum([1 for r in results if r is True]) if successes != num_images: - logger.error(_("Failed to successfully cache all " - "images in queue.")) + LOG.error(_("Failed to successfully cache all " + "images in queue.")) return False - logger.info(_("Successfully cached all %d images"), num_images) + LOG.info(_("Successfully cached all %d images"), num_images) return True diff --git a/glance/image_cache/pruner.py b/glance/image_cache/pruner.py index 2620936263..72ae4a373b 100644 --- a/glance/image_cache/pruner.py +++ b/glance/image_cache/pruner.py @@ -19,12 +19,8 @@ Prunes the Image Cache """ -import logging - from glance.image_cache import base -logger = logging.getLogger(__name__) - class Pruner(base.CacheApp): diff --git a/glance/notifier/notify_kombu.py b/glance/notifier/notify_kombu.py index 537b39058a..7f8decad17 100644 --- a/glance/notifier/notify_kombu.py +++ b/glance/notifier/notify_kombu.py @@ -24,7 +24,7 @@ import kombu.entity from glance.notifier import strategy from glance.openstack.common import cfg -logger = logging.getLogger('glance.notifier.notify_kombu') +LOG = logging.getLogger(__name__) rabbit_opts = [ cfg.StrOpt('rabbit_host', default='localhost'), @@ -84,12 +84,12 @@ class RabbitStrategy(strategy.Strategy): log_info['hostname'] = CONF.rabbit_host log_info['port'] = CONF.rabbit_port if self.connection: - logger.info(_("Reconnecting to AMQP server on " - "%(hostname)s:%(port)d") % log_info) + LOG.info(_("Reconnecting to AMQP server on " + "%(hostname)s:%(port)d") % log_info) self._close() else: - logger.info(_("Connecting to AMQP server on " - "%(hostname)s:%(port)d") % log_info) + LOG.info(_("Connecting to AMQP server on " + "%(hostname)s:%(port)d") % log_info) self.connection = kombu.connection.BrokerConnection( hostname=CONF.rabbit_host, port=CONF.rabbit_port, @@ -117,8 +117,8 @@ class RabbitStrategy(strategy.Strategy): name=routing_key, routing_key=routing_key) queue.declare() - logger.info(_("Connected to AMQP server on " - "%(hostname)s:%(port)d") % log_info) + LOG.info(_("Connected to AMQP server on " + "%(hostname)s:%(port)d") % log_info) def reconnect(self): """Handles reconnecting and re-establishing queues.""" @@ -146,9 +146,9 @@ class RabbitStrategy(strategy.Strategy): log_info['port'] = CONF.rabbit_port if self.max_retries and self.retry_attempts >= self.max_retries: - logger.exception(_('Unable to connect to AMQP server on ' - '%(hostname)s:%(port)d after %(max_retries)d ' - 'tries: %(err_str)s') % log_info) + LOG.exception(_('Unable to connect to AMQP server on ' + '%(hostname)s:%(port)d after %(max_retries)d ' + 'tries: %(err_str)s') % log_info) if self.connection: self._close() raise KombuMaxRetriesReached @@ -158,16 +158,16 @@ class RabbitStrategy(strategy.Strategy): sleep_time = min(sleep_time, self.retry_max_backoff) log_info['sleep_time'] = sleep_time - logger.exception(_('AMQP server on %(hostname)s:%(port)d is' - ' unreachable: %(err_str)s. Trying again in ' - '%(sleep_time)d seconds.') % log_info) + LOG.exception(_('AMQP server on %(hostname)s:%(port)d is' + ' unreachable: %(err_str)s. Trying again in ' + '%(sleep_time)d seconds.') % log_info) time.sleep(sleep_time) def log_failure(self, msg, priority): """Fallback to logging when we can't send to rabbit.""" message = _('Notification with priority %(priority)s failed: ' 'msg=%(msg)s') - logger.error(message % {'msg': msg, 'priority': priority}) + LOG.error(message % {'msg': msg, 'priority': priority}) def _send_message(self, msg, routing_key): """Send a message. Caller needs to catch exceptions for retry.""" @@ -204,7 +204,7 @@ class RabbitStrategy(strategy.Strategy): if 'timeout' not in str(e): raise - logger.exception(_("Unable to send notification: %s") % str(e)) + LOG.exception(_("Unable to send notification: %s") % str(e)) try: self.reconnect() diff --git a/glance/notifier/notify_log.py b/glance/notifier/notify_log.py index 685864f439..46e76ba4ec 100644 --- a/glance/notifier/notify_log.py +++ b/glance/notifier/notify_log.py @@ -24,7 +24,7 @@ class LoggingStrategy(strategy.Strategy): """A notifier that calls logging when called.""" def __init__(self): - self.logger = logging.getLogger('glance.notifier.logging_notifier') + self.logger = logging.getLogger(__name__) def warn(self, msg): self.logger.warn(msg) diff --git a/glance/notifier/notify_qpid.py b/glance/notifier/notify_qpid.py index 6e4018560c..f0bd511da7 100644 --- a/glance/notifier/notify_qpid.py +++ b/glance/notifier/notify_qpid.py @@ -22,7 +22,7 @@ import qpid.messaging from glance.notifier import strategy from glance.openstack.common import cfg -logger = logging.getLogger('glance.notifier.notify_qpid') +LOG = logging.getLogger(__name__) qpid_opts = [ cfg.StrOpt('qpid_notification_exchange', @@ -106,7 +106,7 @@ class QpidStrategy(strategy.Strategy): self.connection.tcp_nodelay = CONF.qpid_tcp_nodelay self.connection.open() self.session = self.connection.session() - logger.info(_('Connected to AMQP server on %s') % self.broker) + LOG.info(_('Connected to AMQP server on %s') % self.broker) self.sender_info = self._sender("info") self.sender_warn = self._sender("warn") diff --git a/glance/registry/__init__.py b/glance/registry/__init__.py index e66d6a5c6d..f095d2b1af 100644 --- a/glance/registry/__init__.py +++ b/glance/registry/__init__.py @@ -26,7 +26,7 @@ from glance.common import exception from glance.openstack.common import cfg from glance.registry import client -logger = logging.getLogger('glance.registry') +LOG = logging.getLogger(__name__) registry_addr_opts = [ cfg.StrOpt('registry_host', default='0.0.0.0'), @@ -70,11 +70,11 @@ def configure_registry_client(): host, port = CONF.registry_host, CONF.registry_port except cfg.ConfigFileValueError: msg = _("Configuration option was not valid") - logger.error(msg) + LOG.error(msg) raise exception.BadRegistryConnectionConfiguration(msg) except IndexError: msg = _("Could not find required configuration option") - logger.error(msg) + LOG.error(msg) raise exception.BadRegistryConnectionConfiguration(msg) _CLIENT_HOST = host @@ -134,20 +134,20 @@ def get_image_metadata(context, image_id): def add_image_metadata(context, image_meta): - logger.debug(_("Adding image metadata...")) + LOG.debug(_("Adding image metadata...")) c = get_registry_client(context) return c.add_image(image_meta) def update_image_metadata(context, image_id, image_meta, purge_props=False): - logger.debug(_("Updating image metadata for image %s..."), image_id) + LOG.debug(_("Updating image metadata for image %s..."), image_id) c = get_registry_client(context) return c.update_image(image_id, image_meta, purge_props) def delete_image_metadata(context, image_id): - logger.debug(_("Deleting image metadata for image %s..."), image_id) + LOG.debug(_("Deleting image metadata for image %s..."), image_id) c = get_registry_client(context) return c.delete_image(image_id) diff --git a/glance/registry/api/v1/images.py b/glance/registry/api/v1/images.py index 03f9a53219..b7c150a221 100644 --- a/glance/registry/api/v1/images.py +++ b/glance/registry/api/v1/images.py @@ -31,7 +31,7 @@ import glance.db from glance.openstack.common import timeutils -logger = logging.getLogger('glance.registry.api.v1.images') +LOG = logging.getLogger(__name__) CONF = cfg.CONF @@ -276,7 +276,7 @@ class Controller(object): msg = _("Access by %(user)s to image %(id)s " "denied") % ({'user': req.context.user, 'id': id}) - logger.info(msg) + LOG.info(msg) raise exc.HTTPNotFound() return dict(image=make_image_dict(image)) @@ -301,13 +301,13 @@ class Controller(object): # that it exists msg = _("Access by %(user)s to delete public image %(id)s denied") args = {'user': req.context.user, 'id': id} - logger.info(msg % args) + LOG.info(msg % args) raise exc.HTTPForbidden() except exception.Forbidden: msg = _("Access by %(user)s to delete private image %(id)s denied") args = {'user': req.context.user, 'id': id} - logger.info(msg % args) + LOG.info(msg % args) return exc.HTTPNotFound() except exception.NotFound: @@ -344,12 +344,12 @@ class Controller(object): return dict(image=make_image_dict(image_data)) except exception.Duplicate: msg = (_("Image with identifier %s already exists!") % id) - logger.error(msg) + LOG.error(msg) return exc.HTTPConflict(msg) except exception.Invalid, e: msg = (_("Failed to add image metadata. " "Got error: %(e)s") % locals()) - logger.error(msg) + LOG.error(msg) return exc.HTTPBadRequest(msg) @utils.mutating @@ -371,8 +371,8 @@ class Controller(object): purge_props = req.headers.get("X-Glance-Registry-Purge-Props", "false") try: - logger.debug(_("Updating image %(id)s with metadata: " - "%(image_data)r") % locals()) + LOG.debug(_("Updating image %(id)s with metadata: " + "%(image_data)r") % locals()) if purge_props == "true": updated_image = self.db_api.image_update(req.context, id, image_data, True) @@ -383,7 +383,7 @@ class Controller(object): except exception.Invalid, e: msg = (_("Failed to update image metadata. " "Got error: %(e)s") % locals()) - logger.error(msg) + LOG.error(msg) return exc.HTTPBadRequest(msg) except exception.NotFound: raise exc.HTTPNotFound(body='Image not found', @@ -391,14 +391,14 @@ class Controller(object): content_type='text/plain') except exception.ForbiddenPublicImage: msg = _("Access by %(user)s to update public image %(id)s denied") - logger.info(msg % {'user': req.context.user, 'id': id}) + LOG.info(msg % {'user': req.context.user, 'id': id}) raise exc.HTTPForbidden() except exception.Forbidden: # If it's private and doesn't belong to them, don't let on # that it exists msg = _("Access by %(user)s to update private image %(id)s denied") - logger.info(msg % {'user': req.context.user, 'id': id}) + LOG.info(msg % {'user': req.context.user, 'id': id}) raise exc.HTTPNotFound(body='Image not found', request=req, content_type='text/plain') diff --git a/glance/registry/api/v1/members.py b/glance/registry/api/v1/members.py index 5889c8ce25..2234454319 100644 --- a/glance/registry/api/v1/members.py +++ b/glance/registry/api/v1/members.py @@ -25,7 +25,7 @@ from glance.common import wsgi import glance.db -logger = logging.getLogger('glance.registry.api.v1.members') +LOG = logging.getLogger(__name__) class Controller(object): @@ -48,7 +48,7 @@ class Controller(object): msg = _("Access by %(user)s to image %(id)s " "denied") % ({'user': req.context.user, 'id': image_id}) - logger.info(msg) + LOG.info(msg) raise webob.exc.HTTPNotFound() return dict(members=make_member_list(image['members'], @@ -82,7 +82,7 @@ class Controller(object): msg = _("Access by %(user)s to image %(id)s " "denied") % ({'user': req.context.user, 'id': image_id}) - logger.info(msg) + LOG.info(msg) raise webob.exc.HTTPNotFound() # Can they manipulate the membership? @@ -184,7 +184,7 @@ class Controller(object): msg = _("Access by %(user)s to image %(id)s " "denied") % ({'user': req.context.user, 'id': image_id}) - logger.info(msg) + LOG.info(msg) raise webob.exc.HTTPNotFound() # Can they manipulate the membership? @@ -239,7 +239,7 @@ class Controller(object): msg = _("Access by %(user)s to image %(id)s " "denied") % ({'user': req.context.user, 'id': image_id}) - logger.info(msg) + LOG.info(msg) raise webob.exc.HTTPNotFound() # Can they manipulate the membership? diff --git a/glance/store/__init__.py b/glance/store/__init__.py index 3ec9baf99c..0c2824ea46 100644 --- a/glance/store/__init__.py +++ b/glance/store/__init__.py @@ -27,7 +27,7 @@ from glance.openstack.common import importutils from glance import registry from glance.store import location -logger = logging.getLogger('glance.store') +LOG = logging.getLogger(__name__) store_opts = [ cfg.ListOpt('known_stores', @@ -146,7 +146,7 @@ class Indexable(object): def _get_store_class(store_entry): store_cls = None try: - logger.debug("Attempting to import store %s", store_entry) + LOG.debug("Attempting to import store %s", store_entry) store_cls = importutils.import_class(store_entry) except exception.NotFound: raise BackendException('Unable to load store. ' @@ -174,8 +174,8 @@ def create_stores(): % store_cls) else: if store_cls not in STORES: - logger.debug("Registering store %s with schemes %s", - store_cls, schemes) + LOG.debug("Registering store %s with schemes %s", + store_cls, schemes) STORES[store_cls] = store_instance scheme_map = {} for scheme in schemes: @@ -187,7 +187,7 @@ def create_stores(): location.register_scheme_map(scheme_map) store_count += 1 else: - logger.debug("Store %s already registered", store_cls) + LOG.debug("Store %s already registered", store_cls) return store_count @@ -269,7 +269,7 @@ def schedule_delete_from_backend(uri, context, image_id, **kwargs): exc_type = sys.exc_info()[0].__name__ msg = (_("Failed to delete image at %s from store (%s)") % (uri, exc_type)) - logger.error(msg) + LOG.error(msg) finally: # avoid falling through to the delayed deletion logic return diff --git a/glance/store/base.py b/glance/store/base.py index a795f8d984..706d5a96d9 100644 --- a/glance/store/base.py +++ b/glance/store/base.py @@ -22,7 +22,7 @@ import logging from glance.common import exception from glance.openstack.common import importutils -logger = logging.getLogger('glance.store.base') +LOG = logging.getLogger(__name__) class Store(object): @@ -41,7 +41,7 @@ class Store(object): except exception.BadStoreConfiguration: msg = _("Failed to configure store correctly. " "Disabling add method.") - logger.error(msg) + LOG.error(msg) self.add = self.add_disabled def configure(self): @@ -64,7 +64,7 @@ class Store(object): """ if not self.store_location_class: class_name = "%s.StoreLocation" % (self.__module__) - logger.debug("Late loading location class %s", class_name) + LOG.debug("Late loading location class %s", class_name) self.store_location_class = importutils.import_class(class_name) return self.store_location_class diff --git a/glance/store/filesystem.py b/glance/store/filesystem.py index a9d75335fb..200a84d2bb 100644 --- a/glance/store/filesystem.py +++ b/glance/store/filesystem.py @@ -32,7 +32,7 @@ import glance.store import glance.store.base import glance.store.location -logger = logging.getLogger('glance.store.filesystem') +LOG = logging.getLogger(__name__) datadir_opt = cfg.StrOpt('filesystem_store_datadir') @@ -63,7 +63,7 @@ class StoreLocation(glance.store.location.StoreLocation): path = (pieces.netloc + pieces.path).strip() if path == '': reason = _("No path specified in URI: %s") % uri - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri('No path specified') self.path = path @@ -116,19 +116,19 @@ class Store(glance.store.base.Store): if self.datadir is None: reason = (_("Could not find %s in configuration options.") % 'filesystem_store_datadir') - logger.error(reason) + LOG.error(reason) raise exception.BadStoreConfiguration(store_name="filesystem", reason=reason) if not os.path.exists(self.datadir): msg = _("Directory to write image files does not exist " "(%s). Creating.") % self.datadir - logger.info(msg) + LOG.info(msg) try: os.makedirs(self.datadir) except IOError: reason = _("Unable to create datadir: %s") % self.datadir - logger.error(reason) + LOG.error(reason) raise exception.BadStoreConfiguration(store_name="filesystem", reason=reason) @@ -148,7 +148,7 @@ class Store(glance.store.base.Store): raise exception.NotFound(_("Image file %s not found") % filepath) else: msg = _("Found image at %s. Returning in ChunkedFile.") % filepath - logger.debug(msg) + LOG.debug(msg) return (ChunkedFile(filepath), None) def delete(self, location): @@ -166,7 +166,7 @@ class Store(glance.store.base.Store): fn = loc.path if os.path.exists(fn): try: - logger.debug(_("Deleting image at %(fn)s") % locals()) + LOG.debug(_("Deleting image at %(fn)s") % locals()) os.unlink(fn) except OSError: raise exception.Forbidden(_("You cannot delete file %s") % fn) @@ -218,6 +218,6 @@ class Store(glance.store.base.Store): checksum_hex = checksum.hexdigest() - logger.debug(_("Wrote %(bytes_written)d bytes to %(filepath)s with " - "checksum %(checksum_hex)s") % locals()) + LOG.debug(_("Wrote %(bytes_written)d bytes to %(filepath)s with " + "checksum %(checksum_hex)s") % locals()) return ('file://%s' % filepath, bytes_written, checksum_hex) diff --git a/glance/store/http.py b/glance/store/http.py index 927aa58d27..c2d1d00d04 100644 --- a/glance/store/http.py +++ b/glance/store/http.py @@ -23,7 +23,7 @@ from glance.common import exception import glance.store.base import glance.store.location -logger = logging.getLogger(__name__) +LOG = logging.getLogger(__name__) class StoreLocation(glance.store.location.StoreLocation): @@ -78,13 +78,13 @@ class StoreLocation(glance.store.location.StoreLocation): except ValueError: reason = (_("Credentials '%s' not well-formatted.") % "".join(creds)) - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() else: self.user = None if netloc == '': reason = _("No address specified in HTTP URL") - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri(message=reason) self.netloc = netloc self.path = path diff --git a/glance/store/location.py b/glance/store/location.py index 5aad4793ea..9b88330c86 100644 --- a/glance/store/location.py +++ b/glance/store/location.py @@ -45,7 +45,7 @@ import urlparse from glance.common import exception from glance.common import utils -logger = logging.getLogger('glance.store.location') +LOG = logging.getLogger(__name__) SCHEME_TO_CLS_MAP = {} @@ -81,9 +81,9 @@ def register_scheme_map(scheme_map): known list of schemes. """ for (k, v) in scheme_map.items(): - logger.debug("Registering scheme %s with %s", k, v) + LOG.debug("Registering scheme %s with %s", k, v) if k in SCHEME_TO_CLS_MAP: - logger.warn("Overwriting scheme %s with %s", k, v) + LOG.warn("Overwriting scheme %s with %s", k, v) SCHEME_TO_CLS_MAP[k] = v diff --git a/glance/store/rbd.py b/glance/store/rbd.py index 6516f6b50e..e63341fae2 100644 --- a/glance/store/rbd.py +++ b/glance/store/rbd.py @@ -41,7 +41,7 @@ DEFAULT_CONFFILE = '' # librados will locate the default conf file DEFAULT_USER = None # let librados decide based on the Ceph conf file DEFAULT_CHUNKSIZE = 4 # in MiB -logger = logging.getLogger('glance.store.rbd') +LOG = logging.getLogger(__name__) rbd_opts = [ cfg.IntOpt('rbd_store_chunk_size', default=DEFAULT_CHUNKSIZE), @@ -71,7 +71,7 @@ class StoreLocation(glance.store.location.StoreLocation): def parse_uri(self, uri): if not uri.startswith('rbd://'): reason = _('URI must start with rbd://') - logger.error(_("Invalid URI: %(uri), %(reason)") % locals()) + LOG.error(_("Invalid URI: %(uri), %(reason)") % locals()) raise exception.BadStoreUri(message=reason) self.image = uri[6:] @@ -133,7 +133,7 @@ class Store(glance.store.base.Store): self.conf_file = str(CONF.rbd_store_ceph_conf) except cfg.ConfigFileValueError, e: reason = _("Error in store configuration: %s") % e - logger.error(reason) + LOG.error(reason) raise exception.BadStoreConfiguration(store_name='rbd', reason=reason) @@ -170,8 +170,8 @@ class Store(glance.store.base.Store): with rados.Rados(conffile=self.conf_file, rados_id=self.user) as conn: with conn.open_ioctx(self.pool) as ioctx: order = int(math.log(self.chunk_size, 2)) - logger.debug('creating image %s with order %d', - image_name, order) + LOG.debug('creating image %s with order %d', + image_name, order) try: rbd.RBD().create(ioctx, image_name, image_size, order) except rbd.ImageExists: diff --git a/glance/store/s3.py b/glance/store/s3.py index fac709e609..6fd245b7b5 100644 --- a/glance/store/s3.py +++ b/glance/store/s3.py @@ -31,7 +31,7 @@ import glance.store import glance.store.base import glance.store.location -logger = logging.getLogger('glance.store.s3') +LOG = logging.getLogger(__name__) s3_opts = [ cfg.StrOpt('s3_store_host'), @@ -111,7 +111,7 @@ class StoreLocation(glance.store.location.StoreLocation): "s3+https://accesskey:secretkey@s3.amazonaws.com/bucket/" "key-id" ) - logger.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) + LOG.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlparse(uri) @@ -138,7 +138,7 @@ class StoreLocation(glance.store.location.StoreLocation): self.secretkey = secret_key except IndexError: reason = _("Badly formed S3 credentials %s") % creds - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() else: self.accesskey = None @@ -154,7 +154,7 @@ class StoreLocation(glance.store.location.StoreLocation): raise exception.BadStoreUri() except IndexError: reason = _("Badly formed S3 URI: %s") % uri - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() @@ -241,7 +241,7 @@ class Store(glance.store.base.Store): if not result: reason = _("Could not find %(param)s in configuration " "options.") % locals() - logger.error(reason) + LOG.error(reason) raise exception.BadStoreConfiguration(store_name="s3", reason=reason) return result @@ -298,7 +298,7 @@ class Store(glance.store.base.Store): "key=%(obj_name)s)") % ({'s3_host': loc.s3serviceurl, 'accesskey': loc.accesskey, 'bucket': loc.bucket, 'obj_name': loc.key}) - logger.debug(msg) + LOG.debug(msg) return key @@ -359,7 +359,7 @@ class Store(glance.store.base.Store): "key=%(obj_name)s)") % ({'s3_host': self.s3_host, 'access_key': self.access_key, 'bucket': self.bucket, 'obj_name': obj_name}) - logger.debug(msg) + LOG.debug(msg) key = bucket_obj.new_key(obj_name) @@ -377,7 +377,7 @@ class Store(glance.store.base.Store): msg = _("Writing request body file to temporary file " "for %s") % _sanitize(loc.get_uri()) - logger.debug(msg) + LOG.debug(msg) tmpdir = self.s3_store_object_buffer_dir temp_file = tempfile.NamedTemporaryFile(dir=tmpdir) @@ -389,15 +389,15 @@ class Store(glance.store.base.Store): msg = (_("Uploading temporary file to S3 for %s") % _sanitize(loc.get_uri())) - logger.debug(msg) + LOG.debug(msg) # OK, now upload the data into the key key.set_contents_from_file(open(temp_file.name, 'r+b'), replace=False) size = key.size checksum_hex = checksum.hexdigest() - logger.debug(_("Wrote %(size)d bytes to S3 key named %(obj_name)s " - "with checksum %(checksum_hex)s") % locals()) + LOG.debug(_("Wrote %(size)d bytes to S3 key named %(obj_name)s " + "with checksum %(checksum_hex)s") % locals()) return (loc.get_uri(), size, checksum_hex) @@ -426,7 +426,7 @@ class Store(glance.store.base.Store): "key=%(obj_name)s)") % ({'s3_host': loc.s3serviceurl, 'accesskey': loc.accesskey, 'bucket': loc.bucket, 'obj_name': loc.key}) - logger.debug(msg) + LOG.debug(msg) return key.delete() @@ -443,7 +443,7 @@ def get_bucket(conn, bucket_id): bucket = conn.get_bucket(bucket_id) if not bucket: msg = _("Could not find bucket with ID %(bucket_id)s") % locals() - logger.error(msg) + LOG.error(msg) raise exception.NotFound(msg) return bucket @@ -507,6 +507,6 @@ def get_key(bucket, obj): key = bucket.get_key(obj) if not key or not key.exists(): msg = _("Could not find key %(obj)s in bucket %(bucket)s") % locals() - logger.error(msg) + LOG.error(msg) raise exception.NotFound(msg) return key diff --git a/glance/store/scrubber.py b/glance/store/scrubber.py index 5acfdf901c..d62afbfbc9 100644 --- a/glance/store/scrubber.py +++ b/glance/store/scrubber.py @@ -31,7 +31,7 @@ from glance.common import utils from glance.openstack.common import cfg from glance.registry import client -logger = logging.getLogger('glance.store.scrubber') +LOG = logging.getLogger(__name__) scrubber_opts = [ cfg.BoolOpt('cleanup_scrubber', default=False), @@ -44,8 +44,8 @@ CONF.register_opts(scrubber_opts) class Daemon(object): def __init__(self, wakeup_time=300, threads=1000): - logger.info(_("Starting Daemon: wakeup_time=%(wakeup_time)s " - "threads=%(threads)s") % locals()) + LOG.info(_("Starting Daemon: wakeup_time=%(wakeup_time)s " + "threads=%(threads)s") % locals()) self.wakeup_time = wakeup_time self.event = eventlet.event.Event() self.pool = eventlet.greenpool.GreenPool(threads) @@ -58,13 +58,13 @@ class Daemon(object): self.event.wait() except KeyboardInterrupt: msg = _("Daemon Shutdown on KeyboardInterrupt") - logger.info(msg) + LOG.info(msg) def _run(self, application): - logger.debug(_("Runing application")) + LOG.debug(_("Running application")) self.pool.spawn_n(application.run, self.pool, self.event) eventlet.spawn_after(self.wakeup_time, self._run, application) - logger.debug(_("Next run scheduled in %s seconds") % self.wakeup_time) + LOG.debug(_("Next run scheduled in %s seconds") % self.wakeup_time) class Scrubber(object): @@ -77,10 +77,10 @@ class Scrubber(object): host, port = CONF.registry_host, CONF.registry_port - logger.info(_("Initializing scrubber with conf: %s") % - {'datadir': self.datadir, 'cleanup': self.cleanup, - 'cleanup_time': self.cleanup_time, - 'registry_host': host, 'registry_port': port}) + LOG.info(_("Initializing scrubber with conf: %s") % + {'datadir': self.datadir, 'cleanup': self.cleanup, + 'cleanup_time': self.cleanup_time, + 'registry_host': host, 'registry_port': port}) self.registry = client.RegistryClient(host, port) @@ -92,7 +92,7 @@ class Scrubber(object): now = time.time() if not os.path.exists(self.datadir): - logger.info(_("%s does not exist") % self.datadir) + LOG.info(_("%s does not exist") % self.datadir) return delete_work = [] @@ -114,7 +114,7 @@ class Scrubber(object): delete_work.append((id, uri, now)) - logger.info(_("Deleting %s images") % len(delete_work)) + LOG.info(_("Deleting %s images") % len(delete_work)) pool.starmap(self._delete, delete_work) if self.cleanup: @@ -123,11 +123,11 @@ class Scrubber(object): def _delete(self, id, uri, now): file_path = os.path.join(self.datadir, str(id)) try: - logger.debug(_("Deleting %(uri)s") % {'uri': uri}) + LOG.debug(_("Deleting %(uri)s") % {'uri': uri}) store.delete_from_backend(uri) except store.UnsupportedBackend: msg = _("Failed to delete image from store (%(uri)s).") - logger.error(msg % {'uri': uri}) + LOG.error(msg % {'uri': uri}) write_queue_file(file_path, uri, now) self.registry.update_image(id, {'status': 'deleted'}) @@ -145,7 +145,7 @@ class Scrubber(object): if cleanup_time > now: return - logger.info(_("Getting images deleted before %s") % self.cleanup_time) + LOG.info(_("Getting images deleted before %s") % self.cleanup_time) write_queue_file(cleanup_file, 'cleanup', now) filters = {'deleted': True, 'is_public': 'none', @@ -169,7 +169,7 @@ class Scrubber(object): pending_delete['location'], now)) - logger.info(_("Deleting %s images") % len(delete_work)) + LOG.info(_("Deleting %s images") % len(delete_work)) pool.starmap(self._delete, delete_work) diff --git a/glance/store/swift.py b/glance/store/swift.py index dafc39c1c0..a07623ace8 100644 --- a/glance/store/swift.py +++ b/glance/store/swift.py @@ -37,7 +37,7 @@ try: except ImportError: pass -logger = logging.getLogger('glance.store.swift') +LOG = logging.getLogger(__name__) DEFAULT_CONTAINER = 'glance' DEFAULT_LARGE_OBJECT_SIZE = 5 * 1024 # 5GB @@ -128,7 +128,7 @@ class StoreLocation(glance.store.location.StoreLocation): "like so: " "swift+http://user:pass@authurl.com/v1/container/obj" ) - logger.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) + LOG.error(_("Invalid store uri %(uri)s: %(reason)s") % locals()) raise exception.BadStoreUri(message=reason) pieces = urlparse.urlparse(uri) @@ -156,7 +156,7 @@ class StoreLocation(glance.store.location.StoreLocation): if len(cred_parts) != 2: reason = (_("Badly formed credentials '%(creds)s' in Swift " "URI") % locals()) - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() user, key = cred_parts self.user = urllib.unquote(user) @@ -173,7 +173,7 @@ class StoreLocation(glance.store.location.StoreLocation): self.authurl = '/'.join(path_parts) except IndexError: reason = _("Badly formed Swift URI: %s") % uri - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() @property @@ -229,7 +229,7 @@ class Store(glance.store.base.Store): self.large_object_chunk_size = _obj_chunk_size * ONE_MB except cfg.ConfigFileValueError, e: reason = _("Error in configuration conf: %s") % e - logger.error(reason) + LOG.error(reason) raise exception.BadStoreConfiguration(store_name="swift", reason=reason) @@ -306,17 +306,17 @@ class Store(glance.store.base.Store): auth_version = self.auth_version full_auth_url = (auth_url if not auth_url or auth_url.endswith('/') else auth_url + '/') - logger.debug(_("Creating Swift connection with " - "(auth_address=%(full_auth_url)s, user=%(user)s, " - "snet=%(snet)s, auth_version=%(auth_version)s)") % - locals()) + LOG.debug(_("Creating Swift connection with " + "(auth_address=%(full_auth_url)s, user=%(user)s, " + "snet=%(snet)s, auth_version=%(auth_version)s)") % + locals()) tenant_name = None if self.auth_version == '2': tenant_user = user.split(':') if len(tenant_user) != 2: reason = (_("Badly formed tenant:user '%(tenant_user)s' in " "Swift URI") % locals()) - logger.error(reason) + LOG.error(reason) raise exception.BadStoreUri() (tenant_name, user) = tenant_user @@ -329,7 +329,7 @@ class Store(glance.store.base.Store): if not result: reason = (_("Could not find %(param)s in configuration " "options.") % locals()) - logger.error(reason) + LOG.error(reason) raise exception.BadStoreConfiguration(store_name="swift", reason=reason) return result @@ -382,8 +382,8 @@ class Store(glance.store.base.Store): 'user': self.user, 'key': self.key}) - logger.debug(_("Adding image object '%(obj_name)s' " - "to Swift") % locals()) + LOG.debug(_("Adding image object '%(obj_name)s' " + "to Swift") % locals()) try: if image_size > 0 and image_size < self.large_object_size: # Image size is known, and is less than large_object_size. @@ -402,8 +402,8 @@ class Store(glance.store.base.Store): # image_size == 0 is when we don't know the size # of the image. This can occur with older clients # that don't inspect the payload size. - logger.debug(_("Cannot determine image size. Adding as a " - "segmented object to Swift.")) + LOG.debug(_("Cannot determine image size. Adding as a " + "segmented object to Swift.")) total_chunks = '?' checksum = hashlib.md5() @@ -426,16 +426,15 @@ class Store(glance.store.base.Store): self.container, chunk_name, reader, content_length=content_length) bytes_read = reader.bytes_read - logger.debug(_("Wrote chunk %(chunk_id)d/" - "%(total_chunks)s of length %(bytes_read)d " - "to Swift returning MD5 of content: " - "%(chunk_etag)s") - % locals()) + msg = _("Wrote chunk %(chunk_id)d/%(total_chunks)s " + "of length %(bytes_read)d to Swift returning " + "MD5 of content: %(chunk_etag)s") + LOG.debug(msg % locals()) if bytes_read == 0: # Delete the last chunk, because it's of zero size. # This will happen if image_size == 0. - logger.debug(_("Deleting final zero-length chunk")) + LOG.debug(_("Deleting final zero-length chunk")) swift_conn.delete_object(self.container, chunk_name) break @@ -474,8 +473,8 @@ class Store(glance.store.base.Store): raise exception.Duplicate(_("Swift already has an image at " "location %s") % location.get_uri()) msg = (_("Failed to add object to Swift.\n" - "Got error from Swift: %(e)s") % locals()) - logger.error(msg) + "Got error from Swift: %(e)s") % locals()) + LOG.error(msg) raise glance.store.BackendException(msg) def delete(self, location): diff --git a/glance/tests/unit/test_notifier.py b/glance/tests/unit/test_notifier.py index cee4240c5f..957e6dd55b 100644 --- a/glance/tests/unit/test_notifier.py +++ b/glance/tests/unit/test_notifier.py @@ -50,7 +50,7 @@ class TestLoggingNotifier(utils.BaseTestCase): super(TestLoggingNotifier, self).setUp() self.config(notifier_strategy="logging") self.called = False - self.logger = logging.getLogger("glance.notifier.logging_notifier") + self.logger = logging.getLogger("glance.notifier.notify_log") self.notifier = notifier.Notifier() def _called(self, msg): diff --git a/glance/tests/unit/v1/test_api.py b/glance/tests/unit/v1/test_api.py index 01aa6162d9..d0104d1dbf 100644 --- a/glance/tests/unit/v1/test_api.py +++ b/glance/tests/unit/v1/test_api.py @@ -71,7 +71,7 @@ class TestRegistryDb(test_utils.BaseTestCase): if 'Error configuring registry database' in msg: self.log_written = True - self.stubs.Set(db_api.logger, 'error', fake_log_error) + self.stubs.Set(db_api.LOG, 'error', fake_log_error) try: api_obj = rserver.API(routes.Mapper()) except exc.ArgumentError: diff --git a/tools/migrate_image_owners.py b/tools/migrate_image_owners.py index 9a58bcf567..f9f54ab3e3 100644 --- a/tools/migrate_image_owners.py +++ b/tools/migrate_image_owners.py @@ -11,9 +11,9 @@ import glance.registry.context import glance.db.sqlalchemy.api as db_api -logger = logging.getLogger(__name__) -logger.addHandler(logging.StreamHandler()) -logger.setLevel(logging.DEBUG) +LOG = logging.getLogger(__name__) +LOG.addHandler(logging.StreamHandler()) +LOG.setLevel(logging.DEBUG) def get_owner_map(ksclient, owner_is_tenant=True): @@ -32,20 +32,20 @@ def build_image_owner_map(owner_map, db, context): owner_name = image['owner'] if not owner_name: - logger.info('Image %s has no owner. Skipping.' % image_id) + LOG.info('Image %s has no owner. Skipping.' % image_id) continue try: owner_id = owner_map[owner_name] except KeyError: msg = 'Image %s owner %s was not found. Skipping.' - logger.error(msg % (image_id, owner_name)) + LOG.error(msg % (image_id, owner_name)) continue image_owner_map[image_id] = owner_id msg = 'Image %s owner %s -> %s' % (image_id, owner_name, owner_id) - logger.info(msg) + LOG.info(msg) return image_owner_map @@ -53,7 +53,7 @@ def build_image_owner_map(owner_map, db, context): def update_image_owners(image_owner_map, db, context): for (image_id, image_owner) in image_owner_map.items(): db.image_update(context, image_id, {'owner': image_owner}) - logger.info('Image %s successfully updated.' % image_id) + LOG.info('Image %s successfully updated.' % image_id) if __name__ == "__main__": @@ -83,7 +83,7 @@ if __name__ == "__main__": admin_password = config.keystone_admin_password if not (auth_uri and admin_tenant_name and admin_user and admin_password): - logger.critical('Missing authentication arguments') + LOG.critical('Missing authentication arguments') sys.exit(1) ks = keystoneclient.v2_0.client.Client(username=admin_user,