]> kaliko git repositories - mpd-sima.git/commitdiff
Add logger
authorkaliko <efrim@azylum.org>
Sun, 22 Sep 2013 08:34:17 +0000 (10:34 +0200)
committerkaliko <efrim@azylum.org>
Sun, 22 Sep 2013 08:34:17 +0000 (10:34 +0200)
launch
sima/client.py
sima/core.py
sima/lib/logger.py [new file with mode: 0644]

diff --git a/launch b/launch
index 83ba3bad9208d6e0cbe6cc1f9c14b4b60d1d079f..d6544b7c8acd6f09ccecf866f4c5ff48dfcad89b 100755 (executable)
--- a/launch
+++ b/launch
@@ -2,13 +2,20 @@
 # -*- coding: utf-8 -*-
 
 def main():
+    from logging import getLogger
+    ##
     from sima import core
     from sima.plugins.crop import Crop
+    from sima.lib.logger import set_logger
+    ##
+    set_logger(log_level='debug')
+    logger = getLogger('sima')
     m = core.Sima()
     m.register_plugin(Crop)
     try:
         m.run()
     except KeyboardInterrupt:
+        logger.info('Caught KeyboardInterrupt, stopping')
         m.shutdown()
 
 
index e19a5aafdabbdce12ad18e747eb5d8c16e5f83ea..331c02c29bdef31e686a51ecf4a7c1a277b7d5a5 100644 (file)
@@ -115,14 +115,6 @@ class PlayerClient(Player):
         except (MPDError, IOError) as err:
             raise PlayerError("Couldn't init idle: %s" % err)
 
-    def idle(self):
-        try:
-            self._client.send_idle('database', 'playlist', 'player', 'options')
-            select([self._client], [], [], 60)
-            return self._client.fetch_idle()
-        except (MPDError, IOError) as err:
-            raise PlayerError("Couldn't init idle: %s" % err)
-
     def remove(self, position=0):
         self._client.delete(position)
 
@@ -134,6 +126,7 @@ class PlayerClient(Player):
     def current(self):
         return self.currentsong()
 
+    @property
     def playlist(self):
         """
         Override deprecated MPD playlist command
@@ -192,7 +185,6 @@ class PlayerClient(Player):
         # If that fails, don't worry, just ignore it and disconnect
         except (MPDError, IOError):
             pass
-
         try:
             self._client.disconnect()
         # Disconnecting failed, so use a new client object instead
index 9c96cb521ae0ab82b0535ab8d1ea0be91cf2b759..f07c3e94c788b90723dff4a4fec574532eca0a47 100644 (file)
@@ -1,5 +1,13 @@
 #!/usr/bin/env python3
 # -*- coding: utf-8 -*-
+"""Core Object dealing with plugins and player client
+"""
+
+__version__ = '0.12.0.b'
+__author__ = 'kaliko jack'
+__url__ = 'git://git.kaliko.me/sima.git'
+
+from logging import getLogger
 
 from .client import PlayerClient
 
@@ -8,9 +16,11 @@ class Sima(object):
     """
 
     def __init__(self):
+        self.log = getLogger('sima')
         self.plugins = list()
         self.player = None
         self.connect_player()
+        self.current_track = None
 
     def register_plugin(self, plugin_class):
         self.plugins.append(plugin_class(self))
@@ -20,7 +30,7 @@ class Sima(object):
             getattr(plugin, method)(*args, **kwds)
 
     def connect_player(self):
-        """Instanciate player client and connect it
+        """Instanciate player client and connect
         """
         self.player = PlayerClient()  # Player client
         self.player.connect()
@@ -34,12 +44,11 @@ class Sima(object):
     def run(self):
         """Dispatching callbacks to plugins
         """
-        print(self.player.status())
+        self.log.debug(self.player.status())
         while 42:
             # hanging here untill a monitored event is raised in the player
             changed = self.player.monitor()
-            print(changed)
-            print(self.player.current)
+            self.log.debug(self.player.current)
             if 'playlist' in changed:
                 self.foreach_plugin('callback_playlist')
             if 'player' in changed:
diff --git a/sima/lib/logger.py b/sima/lib/logger.py
new file mode 100644 (file)
index 0000000..7521188
--- /dev/null
@@ -0,0 +1,91 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2009, 2010, 2013 Jack Kaliko <efrim@azylum.org>
+#
+#  This file is part of sima
+#
+#  sima is free software: you can redistribute it and/or modify
+#  it under the terms of the GNU General Public License as published by
+#  the Free Software Foundation, either version 3 of the License, or
+#  (at your option) any later version.
+#
+#  sima is distributed in the hope that it will be useful,
+#  but WITHOUT ANY WARRANTY; without even the implied warranty of
+#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#  GNU General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with sima.  If not, see <http://www.gnu.org/licenses/>.
+#
+#
+
+"""
+Logging facility for sima.
+"""
+
+import logging
+import sys
+
+LOG_FORMATS = {
+        logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) {levelname}: {message}',
+        logging.INFO:  '{asctime} {levelname}: {message}'
+        }
+DATE_FMT = "%Y-%m-%d %H:%M:%S"
+
+
+class LevelFilter(logging.Filter):# Logging facility
+    """
+    Enable logging between two log level by filtering everything < level.
+    """
+
+    def __init__(self, filt_level):
+        logging.Filter.__init__(self)
+        self.level = filt_level
+
+    def filter(self, record):
+        """Defines loglevel"""
+        return record.levelno <= self.level
+
+
+def set_logger(level='info', logfile=None, name='sima'):
+    """
+    logger:
+        level: in debug, info, warning,…
+        file: provides to log to file
+
+    """
+    user_log_level = getattr(logging, level.upper())
+    if user_log_level > logging.DEBUG:
+        log_format = LOG_FORMATS.get(logging.INFO)
+    else:
+        log_format = LOG_FORMATS.get(logging.DEBUG)
+    logg = logging.getLogger(name)
+    formatter = logging.Formatter(log_format, DATE_FMT, '{')
+    logg.setLevel(user_log_level)
+    if logfile:
+        # create file handler
+        fileh = logging.FileHandler(logfile)
+        #fileh.setLevel(user_log_level)
+        fileh.setFormatter(formatter)
+        logg.addHandler(fileh)
+    else:
+        # create console handler with a specified log level (STDOUT)
+        couth = logging.StreamHandler(sys.stdout)
+        #couth.setLevel(user_log_level)
+        couth.addFilter(LevelFilter(logging.WARNING))
+
+        # create console handler with warning log level (STDERR)
+        cerrh = logging.StreamHandler(sys.stderr)
+        #cerrh.setLevel(logging.WARNING)
+        cerrh.setLevel(logging.ERROR)
+
+        # add formatter to the handlers
+        cerrh.setFormatter(formatter)
+        couth.setFormatter(formatter)
+
+        # add the handlers to SIMA_LOGGER
+        logg.addHandler(couth)
+        logg.addHandler(cerrh)
+
+# VIM MODLINE
+# vim: ai ts=4 sw=4 sts=4 expandtab