diff libervia.py @ 439:d52f529a6d42

browser side: use of new log system (first draft): - configuration is hardcoded in libervia.py, it will change in the (hopefuly) near future - log level is DEBUG for the moment, will be changed to INFO when configuration will not be hardcoded anymore - the basic log backend is used, in the future, a console.debug/info/etc should be used instead. A log widget which HTML colors is also an option
author Goffi <goffi@goffi.org>
date Thu, 08 May 2014 17:21:34 +0200
parents bbdbee25123a
children 88461e9c3e47
line wrap: on
line diff
--- a/libervia.py	Thu May 08 17:21:30 2014 +0200
+++ b/libervia.py	Thu May 08 17:21:34 2014 +0200
@@ -18,6 +18,20 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import pyjd  # this is dummy in pyjs
+
+from constants import Const as C
+### logging configuration ###
+from sat.core.log import configure, getLogger
+configure(C.LOG_BACKEND_BASIC,
+          level = C.LOG_LVL_DEBUG,
+          fmt = '[%(name)s / %(levelname)s] %(message)s',
+          output = None,
+          logger = None,
+          colors = False,
+          force_colors = False)
+log = getLogger(__name__)
+###
+
 from pyjamas.ui.RootPanel import RootPanel
 from pyjamas.ui.HTML import HTML
 from pyjamas.ui.KeyboardListener import KEY_ESCAPE
@@ -37,7 +51,6 @@
 
 from sat_frontends.tools.misc import InputHistory
 from sat_frontends.tools.strings import getURLParams
-from constants import Const as C
 from sat.core.i18n import _
 
 
@@ -63,7 +76,7 @@
         if cb:
             if isinstance(cb, tuple):
                 if len(cb) != 2:
-                    print ("ERROR: tuple syntax for bridge.call is (callback, errback), aborting")
+                    log.error("tuple syntax for bridge.call is (callback, errback), aborting")
                     return
                 if cb[0] is not None:
                     self.cb[_id] = cb[0]
@@ -98,14 +111,14 @@
             del self.eb[request_info.id]
         else:
             if code != 0:
-                print ("Internal server error")
+                log.error("Internal server error")
                 """for o in code, error, request_info:
                     dump(o)"""
             else:
                 if isinstance(errobj['message'], dict):
-                    print("Error %s: %s" % (errobj['message']['faultCode'], errobj['message']['faultString']))
+                    log.error("Error %s: %s" % (errobj['message']['faultCode'], errobj['message']['faultString']))
                 else:
-                    print("Error: %s" % errobj['message'])
+                    log.error("%s" % errobj['message'])
 
 
 class RegisterCall(LiberviaJsonProxy):
@@ -159,7 +172,7 @@
 
 class SatWebFrontend(InputHistory):
     def onModuleLoad(self):
-        print "============ onModuleLoad =============="
+        log.info("============ onModuleLoad ==============")
         panels.ChatPanel.registerClass()
         panels.MicroblogPanel.registerClass()
         self.whoami = None
@@ -201,7 +214,7 @@
     def getSelected(self):
         wid = self.tab_panel.getCurrentPanel()
         if not isinstance(wid, WidgetsPanel):
-            print "ERROR: Tab widget is not a WidgetsPanel, can't get selected widget"
+            log.error("Tab widget is not a WidgetsPanel, can't get selected widget")
             return None
         return wid.selected
 
@@ -263,14 +276,14 @@
         return self.avatars_cache[jid_str]
 
     def registerWidget(self, wid):
-        print "Registering", wid.getDebugName()
+        log.debug("Registering %s" % wid.getDebugName())
         self.libervia_widgets.add(wid)
 
     def unregisterWidget(self, wid):
         try:
             self.libervia_widgets.remove(wid)
         except KeyError:
-            print ('WARNING: trying to remove a non registered Widget:', wid.getDebugName())
+            log.warning('trying to remove a non registered Widget: %s' % wid.getDebugName())
 
     def refresh(self):
         """Refresh the general display."""
@@ -346,7 +359,7 @@
 
         def domain_cb(value):
             self._defaultDomain = value
-            print("new account domain: %s" % value)
+            log.info("new account domain: %s" % value)
 
         def domain_eb(value):
             self._defaultDomain = "libervia.org"
@@ -419,7 +432,7 @@
 
     def _getSignalsCB(self, signal_data):
         self.bridge_signals.call('getSignals', self._getSignalsCB)
-        print('Got signal ==> name: %s, params: %s' % (signal_data[0], signal_data[1]))
+        log.debug("Got signal ==> name: %s, params: %s" % (signal_data[0], signal_data[1]))
         name, args = signal_data
         if name == 'personalEvent':
             self._personalEventCb(*args)
@@ -490,7 +503,7 @@
         for publisher in mblogs:
             for mblog in mblogs[publisher]:
                 if not mblog.has_key('content'):
-                    print ("WARNING: No content found in microblog [%s]", mblog)
+                    log.warning("No content found in microblog [%s]" % mblog)
                     continue
                 if mblog.has_key('groups'):
                     _groups = set(mblog['groups'].split() if mblog['groups'] else [])
@@ -537,7 +550,7 @@
         sender = JID(sender).bare
         if event_type == "MICROBLOG":
             if not 'content' in data:
-                print ("WARNING: No content found in microblog data")
+                log.warning("No content found in microblog data")
                 return
             if 'groups' in data:
                 _groups = set(data['groups'].split() if data['groups'] else [])
@@ -567,7 +580,8 @@
             for lib_wid in self.libervia_widgets:
                 if isinstance(lib_wid, panels.MicroblogPanel):
                     lib_wid.removeEntry(data['type'], data['id'])
-            print self.whoami.bare, sender, data['type']
+            log.debug("%s %s %s" % (self.whoami.bare, sender, data['type']))
+
             if sender == self.whoami.bare and data['type'] == 'main_item':
                 for index in xrange(0, len(self.mblog_cache)):
                     entry = self.mblog_cache[index]
@@ -595,7 +609,7 @@
             self.addBlogEntry(mblog_panel, self.whoami.bare, *cache_entry)
 
     def getEntityMBlog(self, entity):
-        print "geting mblog for entity [%s]" % (entity,)
+        log.info("geting mblog for entity [%s]" % (entity,))
         for lib_wid in self.libervia_widgets:
             if isinstance(lib_wid, panels.MicroblogPanel):
                 if lib_wid.isJidAccepted(entity):
@@ -617,7 +631,7 @@
             if isinstance(lib_wid, class_):
                 try:
                     if lib_wid.matchEntity(entity):
-                        print "existing widget found: %s" % lib_wid.getDebugName()
+                        log.debug("existing widget found: %s" % lib_wid.getDebugName())
                         return lib_wid
                 except AttributeError as e:
                     e.stack_list()
@@ -844,7 +858,7 @@
     def sendError(self, errorData):
         dialog.InfoDialog("Error while sending message",
                           "Your message can't be sent", Width="400px").center()
-        print "sendError: %s" % str(errorData)
+        log.error("sendError: %s" % str(errorData))
 
     def send(self, targets, text, extra={}):
         """Send a message to any target type.
@@ -868,7 +882,7 @@
             elif type_ in ("groupchat", "chat"):
                 addresses.append((addr, entities))
             else:
-                print "ERROR: Unknown target type"
+                log.error("Unknown target type")
         if addresses:
             if len(addresses) == 1 and addresses[0][0] == 'to':
                 self.bridge.call('sendMessage', (None, self.sendError), addresses[0][1], text, '', type_, extra)