From f348b768ac5294a10e1bf03a18628c31a0a9efb5 Mon Sep 17 00:00:00 2001 From: kaliko Date: Tue, 21 Mar 2023 17:18:02 +0100 Subject: [PATCH] Cleanup logging --- README.rst | 4 ++++ sid/sid.py | 51 +++++++++++++++++++++++---------------------------- 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/README.rst b/README.rst index 1d724e1..a64e4b7 100644 --- a/README.rst +++ b/README.rst @@ -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, diff --git a/sid/sid.py b/sid/sid.py index 7d2f4b7..19ba57f 100644 --- a/sid/sid.py +++ b/sid/sid.py @@ -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 -- 2.39.2