]> kaliko git repositories - sid.git/commitdiff
Cleanup logging
authorkaliko <kaliko@azylum.org>
Tue, 21 Mar 2023 16:18:02 +0000 (17:18 +0100)
committerkaliko <kaliko@azylum.org>
Tue, 21 Mar 2023 16:23:27 +0000 (17:23 +0100)
README.rst
sid/sid.py

index 1d724e19729a9b63bcc4922bbb0675cc7aff58da..a64e4b7513aad559b429c4186cb397e3f52e0d9d 100644 (file)
@@ -31,9 +31,13 @@ Here is a plain example::
    # -*- coding: utf-8 -*-
 
    import getpass
+   import logging
    from sid.sid import MUCBot
    from sid.ping import Ping
 
+   logging.basicConfig(level=args.loglevel,
+                       format='%(levelname)-8s %(message)s')
+
    JID = 'bot@example.org'
    ROOM = 'room@conf.example.org'
    # Pay attention: if you join the room with the same account/nick,
index 7d2f4b7b362fc166c2cf2c98cd112bda44067f17..19ba57fdc2b2b38b2531fcdef62649b585e8656d 100644 (file)
@@ -13,6 +13,8 @@ import slixmpp
 
 from sid import __url__, __doc__
 
+log = logging.getLogger(__package__)
+
 
 def botcmd(*args, **kwargs):
     """Decorator for bot command functions
@@ -48,19 +50,19 @@ class MUCBot(slixmpp.ClientXMPP):
     #: Defaults to "!"
     prefix = '!'
 
-    def __init__(self, jid, password, room, nick, log_file=None,
+    def __init__(self, jid, password, room, nick,
                  log_level=logging.INFO):
         super(MUCBot, self).__init__(jid, password)
 
         # Clean sphinx autodoc for self documentation
         # (cf. MUCBot.help)
         self.__doc__ = None
-        self.log = logging.getLogger(__package__)
+        self.log = log
         self.plugins = list()
         self.commands = dict()
         self.room = room
         self.nick = nick
-        self.__set_logger(log_file, log_level)
+        self.__set_logger(log_level)
         self.__seen = dict()
         self.register_plugin('xep_0030')  # Service Discovery
         self.register_plugin('xep_0045')  # Multi-User Chat
@@ -86,25 +88,18 @@ class MUCBot(slixmpp.ClientXMPP):
             if inspect.ismethod(value) and \
                getattr(value, '_bot_command', False):
                 name = getattr(value, '_bot_command_name')
-                self.log.debug('Registered command: %s', name)
+                log.debug('Registered command: %s', name)
                 self.commands[name] = value
 
-    def __set_logger(self, log_file=None, log_level=logging.INFO):
-        """Create console/file handler"""
-        log_fd = open(log_file, 'w') if log_file else None
-        chandler = logging.StreamHandler(log_fd)
-        formatter = logging.Formatter(
-            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
-            )
-        chandler.setFormatter(formatter)
-        self.log.addHandler(chandler)
-        self.log.setLevel(log_level)
-        self.log.debug('set logger, log level : %s', log_level)
+    def __set_logger(self, log_level):
+        """Set logging level"""
+        log.setLevel(log_level)
+        log.debug('set logger, log level : %s', log_level)
 
     def disconn(self, event):
         """disconnected handler"""
         msg = ": %s" % event if event else "‽"
-        self.log.info('Disconnected from server%s', msg)
+        log.info('Disconnected from server%s', msg)
         self.connect()
 
     def message(self, msg):
@@ -113,31 +108,31 @@ class MUCBot(slixmpp.ClientXMPP):
         Parses message received to detect :py:obj:`prefix`
         """
         if msg['type'] not in ('groupchat', 'chat'):
-            self.log.warning('Unhandled message')
+            log.warning('Unhandled message')
             return
         if msg['mucnick'] == self.nick:
             return
         body = msg['body'].strip()
         if not body.startswith(MUCBot.prefix):
             return
-        self.log.debug(msg['from'])
+        log.debug(msg['from'])
         if msg['from'] not in self.__seen and msg['type'] == 'chat':
-            self.log.warning('Will not handle direct message'
+            log.warning('Will not handle direct message'
                              'from unseen jid: %s', msg['from'])
             return
         args = body[1:].split()
         cmd = args.pop(0)
         if cmd not in self.commands:
             return
-        self.log.debug('cmd: %s', cmd)
+        log.debug('cmd: %s', cmd)
         if args:
-            self.log.debug('arg: %s', args)
+            log.debug('arg: %s', args)
         try:
             self.commands[cmd](msg, args)
         except Exception as err:
             reply = ''.join(traceback.format_exc())
-            self.log.exception('An error occurred processing: %s: %s', body, reply)
-            if self.log.level < 10 and reply:
+            log.exception('An error occurred processing: %s: %s', body, reply)
+            if log.level < 10 and reply:
                 self.send_message(mto=msg['from'].bare, mbody=reply,
                                   mtype='groupchat')
 
@@ -163,7 +158,7 @@ class MUCBot(slixmpp.ClientXMPP):
         await self.plugin['xep_0045'].join_muc_wait(self.room,
                                          self.nick,
                                          # Do not fetch history
-                                         seconds=0,
+                                         maxstanzas=0,
                                          # If a room password is needed, use:
                                          # password=the_room_password,
                                          )
@@ -178,19 +173,19 @@ class MUCBot(slixmpp.ClientXMPP):
             if inspect.ismethod(value) and \
                getattr(value, '_bot_command', False):
                 name = getattr(value, '_bot_command_name')
-                self.log.debug('Registered command: %s', name)
+                log.debug('Registered command: %s', name)
                 self.commands[name] = value
 
     def foreach_plugin(self, method, *args, **kwds):
         for plugin in self.plugins:
-            self.log.debug('calling %s for %s', method, plugin)
+            log.debug('calling %s for %s', method, plugin)
             getattr(plugin, method)(*args, **kwds)
 
     def shutdown_plugins(self):
         # TODO: also use event session_end|disconnected?
-        self.log.info('shuting down')
+        log.info('shuting down')
         for plugin in self.plugins:
-            self.log.debug('shuting down %s', plugin)
+            log.debug('shuting down %s', plugin)
             getattr(plugin, 'shutdown')()
 
     @botcmd