Browse Source

Allow early utilisation of lodel.logger ( #121 )

http://redmine.labocleo.org/issues/121
Yann Weber 8 years ago
parent
commit
82e9d3c9aa
3 changed files with 29 additions and 25 deletions
  1. 25
    7
      lodel/logger.py
  2. 2
    17
      lodel/plugin/plugins.py
  3. 2
    1
      lodel/settings/settings.py

+ 25
- 7
lodel/logger.py View File

1
 #-*- coding: utf-8 -*-
1
 #-*- coding: utf-8 -*-
2
 
2
 
3
+import copy
3
 import logging, logging.handlers
4
 import logging, logging.handlers
4
 import os.path
5
 import os.path
5
-from lodel.settings import Settings
6
 
6
 
7
 # Variables & constants definitions
7
 # Variables & constants definitions
8
 default_format = '%(asctime)-15s %(levelname)s %(_pathname)s:%(_lineno)s:%(_funcName)s() : %(message)s'
8
 default_format = '%(asctime)-15s %(levelname)s %(_pathname)s:%(_lineno)s:%(_funcName)s() : %(message)s'
10
 SECURITY_LOGLEVEL = 35
10
 SECURITY_LOGLEVEL = 35
11
 logging.addLevelName(SECURITY_LOGLEVEL, 'SECURITY')
11
 logging.addLevelName(SECURITY_LOGLEVEL, 'SECURITY')
12
 handlers = dict() # Handlers list (generated from settings)
12
 handlers = dict() # Handlers list (generated from settings)
13
+##@brief Stores sent messages until module is able to be initialized
14
+msg_buffer = []
13
 
15
 
14
 # Fetching default root logger
16
 # Fetching default root logger
15
 logger = logging.getLogger()
17
 logger = logging.getLogger()
16
 
18
 
17
-# Setting options from Lodel.settings.Settings.logging
19
+##@brief Module initialisation from settings
20
+#@return True if inited else False
18
 def __init_from_settings():
21
 def __init_from_settings():
22
+    try:
23
+        from lodel.settings import Settings
24
+    except Exception:
25
+        return False
26
+    from lodel.settings.settings import Settings as Lodel2Settings
27
+    if not Lodel2Settings.started():
28
+        return False
19
     # capture warning disabled, because the custom format raises error (unable
29
     # capture warning disabled, because the custom format raises error (unable
20
     # to give the _ preffixed arguments to logger resulting into a KeyError
30
     # to give the _ preffixed arguments to logger resulting into a KeyError
21
     # exception )
31
     # exception )
24
     logger.setLevel(logging.DEBUG)
34
     logger.setLevel(logging.DEBUG)
25
     for name in Settings.logging._fields:
35
     for name in Settings.logging._fields:
26
         add_handler(name, getattr(Settings.logging, name))
36
         add_handler(name, getattr(Settings.logging, name))
37
+    return True
27
     
38
     
28
 
39
 
29
 ##@brief Add an handler, identified by a name, to a given logger 
40
 ##@brief Add an handler, identified by a name, to a given logger 
85
         if isinstance(handler, logging.StreamHandler):
96
         if isinstance(handler, logging.StreamHandler):
86
             remove_handler(name)
97
             remove_handler(name)
87
     
98
     
88
-
89
-# Utility functions
99
+#####################
100
+# Utility functions #
101
+#####################
90
 
102
 
91
 ##@brief Generic logging function
103
 ##@brief Generic logging function
92
 # @param lvl int : Log severity
104
 # @param lvl int : Log severity
94
 # @param *args : additional positionnal arguments
106
 # @param *args : additional positionnal arguments
95
 # @param **kwargs : additional named arguments
107
 # @param **kwargs : additional named arguments
96
 def log(lvl, msg, *args, **kwargs):
108
 def log(lvl, msg, *args, **kwargs):
109
+    if len(handlers) == 0: #late initialisation
110
+        if not __init_from_settings():
111
+            s_kwargs = copy.copy(kwargs)
112
+            s_kwargs.update({'lvl': lvl, 'msg':msg})
113
+            msg_buffer.append((s_kwargs, args))
114
+            return
115
+        else:
116
+            for s_kwargs, args in msg_buffer:
117
+                log(*args, **s_kwargs)
97
     caller = logger.findCaller() # Opti warning : small overhead
118
     caller = logger.findCaller() # Opti warning : small overhead
98
     extra = {
119
     extra = {
99
         '_pathname': os.path.abspath(caller[0]),
120
         '_pathname': os.path.abspath(caller[0]),
109
 def error(msg, *args, **kwargs): log(logging.ERROR, msg, *args, **kwargs)
130
 def error(msg, *args, **kwargs): log(logging.ERROR, msg, *args, **kwargs)
110
 def critical(msg, *args, **kwargs): log(logging.CRITICAL, msg, *args, **kwargs)
131
 def critical(msg, *args, **kwargs): log(logging.CRITICAL, msg, *args, **kwargs)
111
 
132
 
112
-# Initialisation triggering
113
-if len(handlers) == 0:
114
-    __init_from_settings()

+ 2
- 17
lodel/plugin/plugins.py View File

9
 
9
 
10
 import plugins
10
 import plugins
11
 from .exceptions import *
11
 from .exceptions import *
12
+from lodel import logger
12
 
13
 
13
 ## @package lodel.plugins Lodel2 plugins management
14
 ## @package lodel.plugins Lodel2 plugins management
14
 #
15
 #
508
         if cls._load_called != []:
509
         if cls._load_called != []:
509
             cls._load_called = []
510
             cls._load_called = []
510
     
511
     
511
-    @classmethod
512
-    ##@brief Browse directory to get plugin
513
-    #@param plugin_path 
514
-    #@return module existing
515
-    def plugin_discover(self, plugin_path):
516
-        res = os.listdir(plugin_path) is not None
517
-        if res:
518
-            dirname = os.path.dirname(plugin_path)
519
-            for f in os.listdir(plugin_path):
520
-                file_name = ''.join(dirname, f)
521
-                if self.is_plugin_dir(file_name):
522
-                    return self.is_plugin_dir(file_name)
523
-                else:
524
-                    self._discover_plugin(file_name)
525
-        else:
526
-            pass
527
-    
528
     ##@brief Reccursively walk throught paths to find plugin, then stores
512
     ##@brief Reccursively walk throught paths to find plugin, then stores
529
     #found plugin in a file...
513
     #found plugin in a file...
530
     #@return a dict {'path_list': [...], 'plugins': { see @ref _discover }}
514
     #@return a dict {'path_list': [...], 'plugins': { see @ref _discover }}
531
     @classmethod
515
     @classmethod
532
     def discover(cls, paths = None):
516
     def discover(cls, paths = None):
517
+        logger.info("Running plugin discover")
533
         if paths is None:
518
         if paths is None:
534
             paths = DEFAULT_PLUGINS_PATH_LIST
519
             paths = DEFAULT_PLUGINS_PATH_LIST
535
         tmp_res = []
520
         tmp_res = []

+ 2
- 1
lodel/settings/settings.py View File

8
 import types # for dynamic bindings
8
 import types # for dynamic bindings
9
 from collections import namedtuple
9
 from collections import namedtuple
10
 
10
 
11
+from lodel import logger
11
 from lodel.plugin.plugins import Plugin, PluginError
12
 from lodel.plugin.plugins import Plugin, PluginError
12
 from lodel.settings.utils import SettingsError, SettingsErrors
13
 from lodel.settings.utils import SettingsError, SettingsErrors
13
 from lodel.settings.validator import SettingValidator, LODEL2_CONF_SPECS
14
 from lodel.settings.validator import SettingValidator, LODEL2_CONF_SPECS
99
 
100
 
100
     @classmethod
101
     @classmethod
101
     def started(cls):
102
     def started(cls):
102
-        return cls.instance is not None
103
+        return cls.instance is not None and cls.instance.__confs is not None
103
 
104
 
104
     ##@brief An utility method that raises if the singleton is not in a good
105
     ##@brief An utility method that raises if the singleton is not in a good
105
     # state
106
     # state

Loading…
Cancel
Save