Commits

Jonathan Kinred  committed 61e6223

Use *args to pass log strings (efficiency, as log mesages won't be string formatted unless they're actually logged). Remove _init_logging to make psphere more useable as a library.

  • Participants
  • Parent commits c19eaec

Comments (0)

Files changed (4)

File psphere/__init__.py

         try:
             # Get the value from the cache
             value, last_update = inst._cache[self.__name__]
-            logger.info("Found cached value for %s" % self.__name__)
+            logger.info("Found cached value for %s", self.__name__)
             # If the value in the cache exceeds the TTL then raise
             # AttributeError so that we retrieve the value again below
             if self.ttl > 0 and now - last_update > self.ttl:
             # We end up here if the value hasn't been cached
             # or the value exceeds the TTL. We call the decorated
             # function to get the value.
-            logger.info("%s is not cached." % self.__name__)
+            logger.info("%s is not cached.", self.__name__)
             value = self.fget(inst)
             try:
                 # See if the instance has a cache attribute
     _valid_attrs = set([])
     def __init__(self, mo_ref, client):
         self._cache = {}
-        logger.debug("===== Have been passed %s as mo_ref: " % mo_ref)
+        logger.debug("===== Have been passed %s as mo_ref: ", mo_ref)
         self._mo_ref = mo_ref
         self._client = client
 
     def _get_dataobject(self, name, multivalued):
         """This function only gets called if the decorated property
         doesn't have a value in the cache."""
-        logger.debug("Querying server for uncached data object %s" % name)
+        logger.debug("Querying server for uncached data object %s", name)
         # This will retrieve the value and inject it into the cache
         self.update_view_data(properties=[name])
         return self._cache[name][0]
     def _get_mor(self, name, multivalued):
         """This function only gets called if the decorated property
         doesn't have a value in the cache."""
-        logger.debug("Querying server for uncached MOR %s" % name)
+        logger.debug("Querying server for uncached MOR %s", name)
         # This will retrieve the value and inject it into the cache
         logger.debug("Getting view for MOR")
         self.update(properties=[name])
         """
         if properties is None:
             properties = []
-        logger.info("Updating view data for object of type %s" % self._mo_ref._type)
+        logger.info("Updating view data for object of type %s",
+                    self._mo_ref._type)
         property_spec = self._client.create('PropertySpec')
         property_spec.type = str(self._mo_ref._type)
         # Determine which properties to retrieve from the server
                 logger.debug("Retrieving all properties")
                 property_spec.all = True
             else:
-                logger.debug("Retrieving %s properties" % len(properties))
+                logger.debug("Retrieving %s properties", len(properties))
                 property_spec.all = False
                 property_spec.pathSet = properties
 
         """Update the local object from the passed in object_content."""
         # A debugging convenience, allows inspection of the object_content
         # that was used to create the object
-        logger.info("Setting view data for a %s" % self.__class__)
+        logger.info("Setting view data for a %s", self.__class__)
         self._object_content = object_content
 
         for dynprop in object_content.propSet:
 
             try:
                 if not len(dynprop.val):
-                    logger.info("Server returned empty value for %s" %
+                    logger.info("Server returned empty value for %s",
                                 dynprop.name)
             except TypeError:
                 # This except allows us to pass over:
                 # TypeError: object of type 'datetime.datetime' has no len()
                 # It will be processed in the next code block
-                logger.info("%s of type %s has no len!" % (dynprop.name,
-                                                            type(dynprop.val)))
+                logger.info("%s of type %s has no len!",
+                            dynprop.name, type(dynprop.val))
                 pass
 
             try:
                 # suds returns a list containing a single item, which
                 # is another list. Use the first item which is the real list
                 logger.info("Setting value of an Array* property")
-                logger.debug("%s being set to %s" % (dynprop.name,
-                                                     dynprop.val[0]))
+                logger.debug("%s being set to %s",
+                             dynprop.name, dynprop.val[0])
                 now = time.time()
                 cache[dynprop.name] = (dynprop.val[0], now)
             else:
                 logger.info("Setting value of a single-valued property")
-                logger.debug("DynamicProperty value is a %s: " %
+                logger.debug("DynamicProperty value is a %s: ",
                              dynprop.val.__class__.__name__)
-                logger.debug("%s being set to %s" % (dynprop.name,
-                                                     dynprop.val))
+                logger.debug("%s being set to %s", dynprop.name, dynprop.val)
                 now = time.time()
                 cache[dynprop.name] = (dynprop.val, now)
 
                      " with %s" % name)
         # Built-ins always use the default behaviour
 #        if name.startswith("__"):
-#            logger.debug("Returning built-in attribute %s" % name)
+#            logger.debug("Returning built-in attribute %s", name)
 #            return object.__getattribute__(self, name)
 
         # Here we must access _client through __getattribute__, if we were
             return object.__getattribute__(self, name)
 
         # Caller has requested a valid SOAP reference
-        logger.debug("Constructing proxy method %s for a %s" %
-                     (name, self._mo_ref._type))
+        logger.debug("Constructing proxy method %s for a %s",
+                     name, self._mo_ref._type)
         def func(**kwargs):
             result = self._client.invoke(name, _this=self._mo_ref,
                                         **kwargs)
-            logger.debug("Invoke returned %s" % result)
+            logger.debug("Invoke returned %s", result)
             return result
 
         return func

File psphere/client.py

                             NotLoggedInError)
 from psphere.managedobjects import ServiceInstance, Task, classmapper
 
-logger = logging.getLogger("psphere")
+logger = logging.getLogger(__name__)
 
 class Client(suds.client.Client):
     """A client for communicating with a VirtualCenter/ESX/ESXi server
     """
     def __init__(self, server=None, username=None, password=None,
                  wsdl_location="local", timeout=30):
-        self._init_logging()
         self._logged_in = False
         if server is None:
             server = _config_value("general", "server")
         try:
             suds.client.Client.__init__(self, wsdl_uri)
         except URLError:
-            logger.critical("Failed to connect to %s" % self.server)
+            logger.critical("Failed to connect to %s", self.server)
             raise
         except IOError:
-            logger.critical("Failed to load the local WSDL from %s" % wsdl_uri)
+            logger.critical("Failed to load the local WSDL from %s", wsdl_uri)
             raise
         except TransportError:
-            logger.critical("Failed to load the remote WSDL from %s" % wsdl_uri)
+            logger.critical("Failed to load the remote WSDL from %s", wsdl_uri)
             raise
         self.options.transport.options.timeout = timeout
         self.set_options(location=url)
         """
         if (self._logged_in is False and
             method not in ["Login", "RetrieveServiceContent"]):
-            logger.critical("Cannot exec %s unless logged in" % method)
+            logger.critical("Cannot exec %s unless logged in", method)
             raise NotLoggedInError("Cannot exec %s unless logged in" % method)
 
         for kwarg in kwargs:
         # We must traverse the result and convert any ManagedObjectReference
         # to a psphere class, this will then be lazy initialised on use
         logger.debug(result.__class__)
-        logger.debug("Result: %s" % result)
-        logger.debug("Length: %s" % len(result))
+        logger.debug("Result: %s", result)
+        logger.debug("Length: %s", len(result))
         if type(result) == list:
             new_result = []
             for item in result:
 
     def _marshal(self, obj):
         """Walks an object and marshals any psphere object into MORs."""
-        logger.debug("Checking if %s needs to be marshalled" % obj)
+        logger.debug("Checking if %s needs to be marshalled", obj)
         if isinstance(obj, ManagedObject):
             logger.debug("obj is a psphere object, converting to MOR")
             return obj._mo_ref
             return new_list
                 
         if not isinstance(obj, suds.sudsobject.Object):
-            logger.debug("%s is not a sudsobject subclass, skipping" % obj)
+            logger.debug("%s is not a sudsobject subclass, skipping", obj)
             return obj
 
         if hasattr(obj, '__iter__'):
     def _unmarshal(self, obj):
         """Walks an object and unmarshals any MORs into psphere objects."""
         if isinstance(obj, suds.sudsobject.Object) is False:
-            logger.debug("%s is not a suds instance, skipping" % obj)
+            logger.debug("%s is not a suds instance, skipping", obj)
             return obj
 
         logger.debug("Processing:")
 
         new_object = obj.__class__()
         for sub_obj in obj:
-            logger.debug("Looking at %s of type %s" % (str(sub_obj), type(sub_obj)))
+            logger.debug("Looking at %s of type %s", sub_obj, type(sub_obj))
 
             if isinstance(sub_obj[1], list):
                 new_embedded_objs = []
                 continue
 
             if not issubclass(sub_obj[1].__class__, suds.sudsobject.Object):
-                logger.debug("%s is not a sudsobject subclass, skipping" %
+                logger.debug("%s is not a sudsobject subclass, skipping",
                              sub_obj[1].__class__)
                 setattr(new_object, sub_obj[0], sub_obj[1])
                 continue
 
-            logger.debug("Obj keylist: %s" % sub_obj[1].__keylist__)
+            logger.debug("Obj keylist: %s", sub_obj[1].__keylist__)
             if "_type" in sub_obj[1].__keylist__:
                 logger.debug("Converting nested MOR to psphere class:")
                 logger.debug(sub_obj[1])
                 kls = classmapper(sub_obj[1]._type)
-                logger.debug("Setting %s.%s to %s" %
-                             (new_object.__class__.__name__, sub_obj[0],
-                              sub_obj[1]))
+                logger.debug("Setting %s.%s to %s",
+                             new_object.__class__.__name__,
+                             sub_obj[0],
+                             sub_obj[1])
                 setattr(new_object, sub_obj[0], kls(sub_obj[1], self))
             else:
                 logger.debug("Didn't find _type in:")
 
         views = []
         for obj_content in obj_contents:
-            logger.debug("In find_entity_view with object of type %s" % obj_content.obj.__class__.__name__)
+            logger.debug("In find_entity_view with object of type %s",
+                         obj_content.obj.__class__.__name__)
             obj_content.obj.update_view_data(properties=properties)
             views.append(obj_content.obj)
 
         # Start the search at the root folder if no begin_entity was given
         if not begin_entity:
             begin_entity = self.sc.rootFolder._mo_ref
-            logger.debug("Using %s" % self.sc.rootFolder._mo_ref)
+            logger.debug("Using %s", self.sc.rootFolder._mo_ref)
 
         property_spec = self.create('PropertySpec')
         property_spec.type = view_type

File psphere/soap.py

 
 from pprint import pprint
 
-log = logging.getLogger(__name__)
+logger = logging.getLogger(__name__)
 
 class VimFault(Exception):
     def __init__(self, fault):
 
         Exception.__init__(self, "%s: %s" % (self.fault_type, self._fault_dict))
 
-def _init_logging(level="INFO", handler=logging.StreamHandler):
-    """Sets the logging level of underlying suds.client."""
-    logger = logging.getLogger("suds.client")
-    logger.addHandler(handler)
-    logger.setLevel(getattr(logging, level))
-    #logging.getLogger("suds.wsdl").setLevel(logging.DEBUG)
-
 
 def get_client(url):
     client = suds.client.Client(url + "/vimService.wsdl")
         # Proxy the method to the suds service
         result = getattr(client.service, method)(**kwargs)
     except AttributeError, e:
-        log.critical("Unknown method: %s" % method)
+        logger.critical("Unknown method: %s", method)
         sys.exit()
     except urllib2.URLError, e:
-        logging.debug(pprint(e))
-        logging.debug("A URL related error occurred while invoking the '%s' "
+        logger.debug(pprint(e))
+        logger.debug("A URL related error occurred while invoking the '%s' "
               "method on the VIM server, this can be caused by "
-              "name resolution or connection problems." % method)
-        logging.debug("The underlying error is: %s" % e.reason[1])
+              "name resolution or connection problems.", method)
+        logger.debug("The underlying error is: %s", e.reason[1])
         sys.exit()
     except suds.client.TransportError, e:
-        logging.debug(pprint(e))
-        logging.debug("TransportError: %s" % e)
+        logger.debug(pprint(e))
+        logger.debug("TransportError: %s", e)
     except suds.WebFault, e:
         # Get the type of fault
         print("Fault: %s" % e.fault.faultstring)

File psphere/template.py

 from psphere import config
 from psphere.errors import TemplateNotFoundError
 
-logger = logging.getLogger("psphere")
+logger = logging.getLogger(__name__)
 
 template_path = os.path.expanduser(config._config_value("general",
                                                         "template_dir"))
     if name is None:
         name = "default"
 
-    logger.info("Loading template with name %s" % name)
+    logger.info("Loading template with name %s", name)
     try:
         template_file = open("%s/%s.yaml" % (template_path, name))
     except IOError:
     template = yaml.safe_load(template_file)
     template_file.close()
     if "extends" in template:
-        logger.debug("Merging %s with %s" % (name, template["extends"]))
+        logger.debug("Merging %s with %s", name, template["extends"])
         template = _merge(load_template(template["extends"]), template)
 
     return template