Clean up PluginManager and complete logging

This commit is contained in:
Tim Bentley 2013-12-14 08:12:41 +00:00
parent d684359e59
commit e93b825ab4
2 changed files with 57 additions and 40 deletions

View File

@ -27,33 +27,64 @@
# Temple Place, Suite 330, Boston, MA 02111-1307 USA # # Temple Place, Suite 330, Boston, MA 02111-1307 USA #
############################################################################### ###############################################################################
""" """
Provide Error Handling Services Provide Error Handling and login Services
""" """
import logging import logging
import inspect
from openlp.core.common import trace_error_handler from openlp.core.common import trace_error_handler
DO_NOT_TRACE_EVENTS = ['timerEvent', 'paintEvent']
class OpenLPMixin(object): class OpenLPMixin(object):
""" """
Base Calling object for OpenLP classes. Base Calling object for OpenLP classes.
""" """
def __init__(self, parent=None): def __init__(self):
super(OpenLPMixin, self).__init__(parent) super().__init__()
print(self.__class__, self.__module__) self.logger = logging.getLogger(self.__module__)
for name, m in inspect.getmembers(self, inspect.ismethod):
if name not in DO_NOT_TRACE_EVENTS:
if not name.startswith("_") and not name.startswith("log_"):
setattr(self, name, self.logging_wrapper(m, self))
def logging_wrapper(self, func, parent):
"""
Code to added debug wrapper to work on called functions within a decorated class.
"""
def wrapped(*args, **kwargs):
if parent.logger.getEffectiveLevel() == logging.DEBUG:
parent.logger.debug("Entering %s" % func.__name__)
try:
return func(*args, **kwargs)
except Exception as e:
if parent.logger.getEffectiveLevel() <= logging.ERROR:
parent.logger.error('Exception in %s : %s' % (func.__name__, e))
raise e
return wrapped
def log_debug(self, message):
"""
Common log debug handler which prints the calling path
"""
self.logger.debug(message)
def log_info(self, message):
"""
Common log info handler which prints the calling path
"""
self.logger.info(message)
def log_error(self, message): def log_error(self, message):
""" """
Common log error handler which prints the calling path Common log error handler which prints the calling path
""" """
log = logging.getLogger(self.__module__) trace_error_handler(self.logger)
trace_error_handler(log) self.logger.error(message)
log.error(message)
def log_exception(self, message): def log_exception(self, message):
""" """
Common log exception handler which prints the calling path Common log exception handler which prints the calling path
""" """
log = logging.getLogger(self.__module__) trace_error_handler(self.logger)
trace_error_handler(log) self.logger.exception(message)
log.exception(message)

View File

@ -31,68 +31,58 @@ Provide plugin management
""" """
import os import os
import sys import sys
import logging
import imp import imp
from openlp.core.lib import Plugin, PluginStatus from openlp.core.lib import Plugin, PluginStatus
from openlp.core.common import AppLocation, Registry from openlp.core.common import AppLocation, Registry, OpenLPMixin
log = logging.getLogger(__name__)
class PluginManager(object): class PluginManager(OpenLPMixin):
""" """
This is the Plugin manager, which loads all the plugins, This is the Plugin manager, which loads all the plugins,
and executes all the hooks, as and when necessary. and executes all the hooks, as and when necessary.
""" """
log.info('Plugin manager loaded')
def __init__(self): def __init__(self):
""" """
The constructor for the plugin manager. Passes the controllers on to The constructor for the plugin manager. Passes the controllers on to
the plugins for them to interact with via their ServiceItems. the plugins for them to interact with via their ServiceItems.
""" """
log.info('Plugin manager Initialising') super(PluginManager, self).__init__()
self.log_info('Plugin manager Initialising')
Registry().register('plugin_manager', self) Registry().register('plugin_manager', self)
Registry().register_function('bootstrap_initialise', self.bootstrap_initialise) Registry().register_function('bootstrap_initialise', self.bootstrap_initialise)
self.base_path = os.path.abspath(AppLocation.get_directory(AppLocation.PluginsDir)) self.base_path = os.path.abspath(AppLocation.get_directory(AppLocation.PluginsDir))
log.debug('Base path %s ', self.base_path) self.log_debug('Base path %s ' % self.base_path)
self.plugins = [] self.plugins = []
log.info('Plugin manager Initialised') self.log_info('Plugin manager Initialised')
def bootstrap_initialise(self): def bootstrap_initialise(self):
""" """
Bootstrap all the plugin manager functions Bootstrap all the plugin manager functions
""" """
log.info('bootstrap_initialise')
self.find_plugins() self.find_plugins()
# hook methods have to happen after find_plugins. Find plugins needs # hook methods have to happen after find_plugins. Find plugins needs
# the controllers hence the hooks have moved from setupUI() to here # the controllers hence the hooks have moved from setupUI() to here
# Find and insert settings tabs # Find and insert settings tabs
log.info('hook settings')
self.hook_settings_tabs() self.hook_settings_tabs()
# Find and insert media manager items # Find and insert media manager items
log.info('hook media')
self.hook_media_manager() self.hook_media_manager()
# Call the hook method to pull in import menus. # Call the hook method to pull in import menus.
log.info('hook menus')
self.hook_import_menu() self.hook_import_menu()
# Call the hook method to pull in export menus. # Call the hook method to pull in export menus.
self.hook_export_menu() self.hook_export_menu()
# Call the hook method to pull in tools menus. # Call the hook method to pull in tools menus.
self.hook_tools_menu() self.hook_tools_menu()
# Call the initialise method to setup plugins. # Call the initialise method to setup plugins.
log.info('initialise plugins')
self.initialise_plugins() self.initialise_plugins()
def find_plugins(self): def find_plugins(self):
""" """
Scan a directory for objects inheriting from the ``Plugin`` class. Scan a directory for objects inheriting from the ``Plugin`` class.
""" """
log.info('Finding plugins')
start_depth = len(os.path.abspath(self.base_path).split(os.sep)) start_depth = len(os.path.abspath(self.base_path).split(os.sep))
present_plugin_dir = os.path.join(self.base_path, 'presentations') present_plugin_dir = os.path.join(self.base_path, 'presentations')
log.debug('finding plugins in %s at depth %d', str(self.base_path), start_depth) self.log_debug('finding plugins in %s at depth %d' % (self.base_path, start_depth))
for root, dirs, files in os.walk(self.base_path): for root, dirs, files in os.walk(self.base_path):
if sys.platform == 'darwin' and root.startswith(present_plugin_dir): if sys.platform == 'darwin' and root.startswith(present_plugin_dir):
# TODO Presentation plugin is not yet working on Mac OS X. # TODO Presentation plugin is not yet working on Mac OS X.
@ -108,7 +98,7 @@ class PluginManager(object):
break break
module_name = name[:-3] module_name = name[:-3]
# import the modules # import the modules
log.debug('Importing %s from %s. Depth %d', module_name, root, this_depth) self.log_debug('Importing %s from %s. Depth %d' % (module_name, root, this_depth))
try: try:
# Use the "imp" library to try to get around a problem with the PyUNO library which # Use the "imp" library to try to get around a problem with the PyUNO library which
# monkey-patches the __import__ function to do some magic. This causes issues with our tests. # monkey-patches the __import__ function to do some magic. This causes issues with our tests.
@ -117,20 +107,21 @@ class PluginManager(object):
# Then load the module (do the actual import) using the details from find_module() # Then load the module (do the actual import) using the details from find_module()
imp.load_module(module_name, fp, path_name, description) imp.load_module(module_name, fp, path_name, description)
except ImportError as e: except ImportError as e:
log.exception('Failed to import module %s on path %s: %s', module_name, path, e.args[0]) self.log_exception('Failed to import module %s on path %s: %s'
% (module_name, path, e.args[0]))
plugin_classes = Plugin.__subclasses__() plugin_classes = Plugin.__subclasses__()
plugin_objects = [] plugin_objects = []
for p in plugin_classes: for p in plugin_classes:
try: try:
plugin = p() plugin = p()
log.debug('Loaded plugin %s', str(p)) self.log_debug('Loaded plugin %s' % str(p))
plugin_objects.append(plugin) plugin_objects.append(plugin)
except TypeError: except TypeError:
log.exception('Failed to load plugin %s', str(p)) self.log_exception('Failed to load plugin %s' % str(p))
plugins_list = sorted(plugin_objects, key=lambda plugin: plugin.weight) plugins_list = sorted(plugin_objects, key=lambda plugin: plugin.weight)
for plugin in plugins_list: for plugin in plugins_list:
if plugin.check_pre_conditions(): if plugin.check_pre_conditions():
log.debug('Plugin %s active', str(plugin.name)) self.log_debug('Plugin %s active' % str(plugin.name))
plugin.set_status() plugin.set_status()
else: else:
plugin.status = PluginStatus.Disabled plugin.status = PluginStatus.Disabled
@ -199,24 +190,21 @@ class PluginManager(object):
Loop through all the plugins and give them an opportunity to Loop through all the plugins and give them an opportunity to
initialise themselves. initialise themselves.
""" """
log.info('Initialise Plugins - Started')
for plugin in self.plugins: for plugin in self.plugins:
log.info('initialising plugins %s in a %s state' % (plugin.name, plugin.is_active())) self.log_info('initialising plugins %s in a %s state' % (plugin.name, plugin.is_active()))
if plugin.is_active(): if plugin.is_active():
plugin.initialise() plugin.initialise()
log.info('Initialisation Complete for %s ' % plugin.name) self.log_info('Initialisation Complete for %s ' % plugin.name)
log.info('Initialise Plugins - Finished')
def finalise_plugins(self): def finalise_plugins(self):
""" """
Loop through all the plugins and give them an opportunity to Loop through all the plugins and give them an opportunity to
clean themselves up clean themselves up
""" """
log.info('finalising plugins')
for plugin in self.plugins: for plugin in self.plugins:
if plugin.is_active(): if plugin.is_active():
plugin.finalise() plugin.finalise()
log.info('Finalisation Complete for %s ' % plugin.name) self.log_info('Finalisation Complete for %s ' % plugin.name)
def get_plugin_by_name(self, name): def get_plugin_by_name(self, name):
""" """
@ -231,7 +219,6 @@ class PluginManager(object):
""" """
Loop through all the plugins and give them an opportunity to handle a new service Loop through all the plugins and give them an opportunity to handle a new service
""" """
log.info('plugins - new service created')
for plugin in self.plugins: for plugin in self.plugins:
if plugin.is_active(): if plugin.is_active():
plugin.new_service_created() plugin.new_service_created()
@ -255,4 +242,3 @@ class PluginManager(object):
return self._main_window return self._main_window
main_window = property(_get_main_window) main_window = property(_get_main_window)