Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add logging support

Nearly all print/write operations have been turned into logging calls, except
for the output of the cli module, which seems to be expected to be print as it.
(ie. it's not a logging task, but a real print task)
  • Loading branch information...
commit 37cfefc2bebfa514bfcb71fe371e76d6874d2b74 1 parent c839888
@multani authored
View
18 sonata/audioscrobbler.py
@@ -275,6 +275,7 @@
import locale
import hashlib
import site
+import logging
import sys
import time
import urllib
@@ -404,6 +405,8 @@ def __init__(self,
client_name=client_name,
client_version=pyscrobbler_version):
+ self.logger = logging.getLogger(__name__)
+
self.audioscrobbler_request_version = audioscrobbler_request_version
self.audioscrobbler_post_version = audioscrobbler_post_version
self.audioscrobbler_request_host = audioscrobbler_request_host
@@ -610,13 +613,15 @@ def __init__(self,
protocol_version=protocol_version,
host=host)
- self.verbose = verbose
+ self.logger = logging.getLogger(__name__)
+ if not verbose:
+ self.logger.setLevel(logging.WARNING)
self.auth_details = {}
self.last_post = None
self.interval = 0
self.cache = []
- self.loglines = []
+ self.loglines = [] # TODO: it somehow duplicates with the logging module
self.last_shake = None
self.authenticated = False
self.updateurl = None
@@ -819,12 +824,14 @@ def nowplaying(self,
url_handle = urllib2.urlopen(req)
except urllib2.HTTPError, error:
self.authenticated = False
- print AudioScrobblerConnectionError('http', error.code, error.msg)
+ self.logger.error(
+ "%s", AudioScrobblerConnectionError('http', error.code, error.msg))
return
except:
code = '000'
message = sys.exc_info()[1]
- print AudioScrobblerConnectionError('network', code, message)
+ self.logger.error(
+ "%s", AudioScrobblerConnectionError('network', code, message))
return
response = url_handle.readlines()
@@ -963,8 +970,7 @@ def log(self, msg):
time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.loglines.append("%s: %s" % (time, msg))
- if self.verbose:
- print self.loglines[-1]
+ self.logger.debug(msg)
def getlog(self, clear=False):
View
23 sonata/cli.py
@@ -1,6 +1,7 @@
import sys
import gettext
+import logging
from optparse import OptionParser
from version import version
@@ -13,6 +14,7 @@
class Args(object):
def __init__(self):
+ self.logger = logging.getLogger(__name__)
self.skip_gui = False
self.start_visibility = None
@@ -81,7 +83,8 @@ def parse(self, argv):
if options.toggle or options.popup or options.fullscreen:
import dbus_plugin as dbus
if not dbus.using_dbus():
- print _("toggle and popup options require D-Bus. Aborting.")
+ self.logger.critical(
+ _("toggle and popup options require D-Bus. Aborting."))
sys.exit(1)
dbus.execute_remote_commands(options.toggle,
@@ -104,12 +107,14 @@ def apply_profile_arg(self, config):
a = self.arg_profile
if a > 0 and a <= len(config.profile_names):
config.profile_num = a-1
- print _("Starting Sonata with profile %s...") % \
- config.profile_names[config.profile_num]
+ self.logger.info(_("Starting Sonata with profile %s...") %
+ config.profile_names[config.profile_num])
else:
- print _("%d is not an available profile number.") % a
- print _("Profile numbers must be between 1 and %d.") % \
- len(config.profile_names)
+ self.logger.critical(
+ _("%d is not an available profile number.") % a)
+ self.logger.critical(
+ _("Profile numbers must be between 1 and %d.") %
+ len(config.profile_names))
sys.exit(1)
@@ -124,6 +129,7 @@ def __init__(self, args):
import mpdhelper as mpdh
import misc
+ self.logger = logging.getLogger(__name__)
self.config = config.Config(_('Default Profile'), _("by") + " %A " + \
_("from") + " %B", library.library_set_data)
self.config.settings_load_real(library.library_set_data)
@@ -147,8 +153,9 @@ def mpd_connect(self):
def execute_cmd(self, cmd):
self.status = mpdh.status(self.client)
if not self.status:
- print _(('Unable to connect to MPD.\nPlease check your Sonata '
- 'preferences or MPD_HOST/MPD_PORT environment variables.'))
+ self.logger.critical(_(
+ 'Unable to connect to MPD.\nPlease check your Sonata '
+ 'preferences or MPD_HOST/MPD_PORT environment variables.'))
sys.exit(1)
self.songinfo = mpdh.currsong(self.client)
View
28 sonata/dbus_plugin.py
@@ -20,6 +20,7 @@
# do something else instead...
"""
+import logging
import sys
try:
@@ -38,6 +39,9 @@
HAVE_DBUS = False
+logger = logging.getLogger(__name__)
+
+
def using_dbus():
return HAVE_DBUS
@@ -99,10 +103,11 @@ def get_session_bus():
try:
return dbus.SessionBus()
except Exception:
- print _(('Sonata failed to connect to the D-BUS session bus: '
- 'Unable to determine the address of the message bus '
- '(try \'man dbus-launch\' and \'man dbus-daemon\' '
- 'for help)")'))
+ logger.error(
+ _('Sonata failed to connect to the D-BUS session bus: '
+ 'Unable to determine the address of the message bus '
+ '(try \'man dbus-launch\' and \'man dbus-daemon\' '
+ 'for help)")'))
raise
@@ -119,11 +124,12 @@ def execute_remote_commands(toggle=False, popup=False, fullscreen=False,
obj.fullscreen(dbus_interface='org.MPD.SonataInterface')
sys.exit()
except Exception:
- print _("Failed to execute remote commands.")
+ logger.warning(_("Failed to execute remote commands."))
if start is None or start:
- print _("Starting Sonata instead...")
+ logger.info(_("Starting Sonata instead..."))
else:
- print _("Maybe Sonata is not running?")
+ # TODO: should we log the exception here?
+ logger.critical(_("Maybe Sonata is not running?"))
sys.exit(1)
@@ -143,14 +149,16 @@ def start_dbus_interface():
pass
elif retval in (dbus_bindings.REQUEST_NAME_REPLY_EXISTS,
dbus_bindings.REQUEST_NAME_REPLY_IN_QUEUE):
- print _(('An instance of Sonata is already running. '
- 'Showing it...'))
+ logger.info(
+ _('An instance of Sonata is already running. '
+ 'Showing it...'))
try:
obj = bus.get_object('org.MPD', '/org/MPD/Sonata')
obj.show(dbus_interface='org.MPD.SonataInterface')
sys.exit()
except Exception:
- print _("Failed to execute remote command.")
+ # TODO: should we log the exception here?
+ logger.critical(_("Failed to execute remote command."))
sys.exit(1)
except Exception:
pass
View
6 sonata/info.py
@@ -3,6 +3,7 @@
import sys
import os
import locale
+import logging
import gtk
import pango
@@ -21,6 +22,7 @@ def __init__(self, config, info_image, linkcolor, on_link_click_cb,
get_playing_song, TAB_INFO, on_image_activate,
on_image_motion_cb, on_image_drop_cb,
album_return_artist_and_tracks, new_tab):
+ self.logger = logging.getLogger(__name__)
self.config = config
self.linkcolor = linkcolor
self.on_link_click_cb = on_link_click_cb
@@ -30,8 +32,8 @@ def __init__(self, config, info_image, linkcolor, on_link_click_cb,
try:
self.enc = locale.getpreferredencoding()
except:
- print ('Locale cannot be found; please set your system\'s locale. '
- 'Aborting...')
+ self.logger.exception("Locale cannot be found; please set your "
+ "system's locale. Aborting...")
sys.exit(1)
self.last_bitrate = None
View
45 sonata/launcher.py
@@ -24,7 +24,12 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
-import sys, platform, locale, gettext, os
+import gettext
+import locale
+import logging
+import os
+import platform
+import sys
def run():
@@ -32,28 +37,35 @@ def run():
# XXX insert the correct sonata package dir in sys.path
+ logging.basicConfig(
+ level=logging.WARNING,
+ format="[%(asctime)s] %(name)s: %(message)s",
+ datefmt="%Y-%m-%d %H:%M:%S",
+ stream=sys.stderr)
+
+ logger = logging.getLogger(__name__)
+
try:
import sonata
except ImportError:
- sys.stderr.write("Python failed to find the sonata modules.\n")
- sys.stderr.write("\nSearched in the following directories:\n" +
- "\n".join(sys.path) + "\n")
- sys.stderr.write("\nPerhaps Sonata is improperly installed?\n")
+ logger.critical("Python failed to find the sonata modules.")
+ logger.critical("Searched in the following directories:\n%s",
+ "\n".join(sys.path))
+ logger.critical("Perhaps Sonata is improperly installed?")
sys.exit(1)
try:
from sonata.version import version
except ImportError:
- sys.stderr.write("Python failed to find the sonata modules.\n")
- sys.stderr.write("\nAn old or incomplete installation was " +
- "found in the following directory:\n" +
- os.path.dirname(sonata.__file__) + "\n")
- sys.stderr.write("\nPerhaps you want to delete it?\n")
+ logger.critical("Python failed to find the sonata modules.")
+ logger.critical("An old or incomplete installation was "
+ "found in the following directory: %s",
+ os.path.dirname(sonata.__file__))
+ logger.critical("Perhaps you want to delete it?")
sys.exit(1)
# XXX check that version.VERSION is what this script was installed for
-
## Apply global fixes:
# the following line is to fix python-zsi 2.0 and thus lyrics in ubuntu:
@@ -84,7 +96,7 @@ def run():
try:
gettext.install('sonata', os.path.join(sonata.__file__.split('/lib')[0], 'share', 'locale'), unicode=1)
except:
- print "Warning: trying to use an old translation"
+ logger.warning("Trying to use an old translation")
gettext.install('sonata', '/usr/share/locale', unicode=1)
gettext.textdomain('sonata')
@@ -93,13 +105,13 @@ def run():
# Test python version:
if sys.version_info < (2,5):
- sys.stderr.write("Sonata requires Python 2.5 or newer. Aborting...\n")
+ logger.critical("Sonata requires Python 2.5 or newer. Aborting...")
sys.exit(1)
try:
import mpd
except:
- sys.stderr.write("Sonata requires python-mpd. Aborting...\n")
+ logger.critical("Sonata requires python-mpd. Aborting...")
sys.exit(1)
@@ -124,7 +136,7 @@ def run():
# importing gtk does sys.setdefaultencoding("utf-8"), sets locale etc.
import gtk
if gtk.pygtk_version < (2, 12, 0):
- sys.stderr.write("Sonata requires PyGTK 2.12.0 or newer. Aborting...\n")
+ logger.critical("Sonata requires PyGTK 2.12.0 or newer. Aborting...")
sys.exit(1)
# fix locale
misc.setlocale()
@@ -134,7 +146,8 @@ class FakeModule(object):
# make sure the ui modules aren't imported
for m in 'gtk', 'pango', 'sonata.ui', 'sonata.breadcrumbs':
if m in sys.modules:
- print "Warning: module %s imported in CLI mode" % m
+ logger.warning(
+ "Module %s imported in CLI mode (it should not)", m)
else:
sys.modules[m] = FakeModule()
# like gtk, set utf-8 encoding of str objects
View
6 sonata/lyricwiki.py
@@ -1,4 +1,5 @@
from HTMLParser import HTMLParser
+import logging
import os
import urllib
import re
@@ -16,6 +17,7 @@
class LyricWiki(object):
def __init__(self):
+ self.logger = logging.getLogger(__name__)
self.lyricServer = None
pluginsystem.plugin_infos.append(BuiltinPlugin(
@@ -70,8 +72,8 @@ def get_content(page):
else:
error = _("Lyrics not found")
self.call_back(callback, error=error)
- except Exception, e:
- print >> sys.stderr, "Error while fetching the lyrics:\n%s" % e
+ except:
+ self.logger.exception("Error while fetching the lyrics")
error = _("Fetching lyrics failed")
self.call_back(callback, error=error)
View
12 sonata/main.py
@@ -21,6 +21,7 @@
import sys
import gettext
+import logging
import os
import warnings
@@ -84,6 +85,8 @@ class Base(object):
### XXX Warning, a long __init__ ahead:
def __init__(self, args, window=None, _sugar=False):
+ self.logger = logging.getLogger(__name__)
+
# The following attributes were used but not defined here before:
self.album_current_artist = None
@@ -935,12 +938,11 @@ def __init__(self, args, window=None, _sugar=False):
if plugin.name not in self.config.known_plugins:
self.config.known_plugins.append(plugin.name)
if plugin.name in consts.DEFAULT_PLUGINS:
- print _("Enabling new plug-in %s..." %
- plugin.name)
+ self.logger.info(
+ _("Enabling new plug-in %s..." % plugin.name))
pluginsystem.set_enabled(plugin, True)
else:
- print _("Found new plug-in %s." %
- plugin.name)
+ self.logger.info(_("Found new plug-in %s." % plugin.name))
### Tab system:
@@ -3472,7 +3474,7 @@ def find_path(self, filename):
full_filename = os.path.join(sys.prefix,
'share', 'pixmaps', filename)
if not full_filename:
- print filename + " cannot be found. Aborting..."
+ self.logger.critical("%r cannot be found. Aborting...", filename)
sys.exit(1)
return full_filename
View
6 sonata/misc.py
@@ -3,9 +3,13 @@
import subprocess
import re
import locale
+import logging
import sys
+logger = logging.getLogger(__name__)
+
+
def convert_time(raw):
# Converts raw time to 'hh:mm:ss' with leading zeros as appropriate
h, m, s = ['%02d' % c for c in (raw / 3600, (raw % 3600) / 60, raw % 60)]
@@ -256,5 +260,5 @@ def setlocale():
# keys for, e.g., playlistinfo() with a turkish locale:
locale.setlocale(locale.LC_CTYPE, "C")
except:
- print "Failed to set locale"
+ logger.exception("Failed to set locale")
sys.exit(1)
View
19 sonata/mpdhelper.py
@@ -1,16 +1,21 @@
import locale
+import logging
import sys
import os
from time import strftime
from misc import remove_list_duplicates
-suppress_errors = False
+logger = logging.getLogger(__name__)
-def suppress_mpd_errors(val):
- global suppress_errors
- suppress_errors = val
+
+def suppress_mpd_errors(suppress_errors):
+ if suppress_errors:
+ # Well, maybe we still want some very bad errors, who knows
+ logger.setLevel(logging.CRITICAL)
+ else:
+ logger.setLevel(logging.NOTSET)
def status(client):
@@ -64,11 +69,9 @@ def conout(s):
def call(mpdclient, mpd_cmd, *mpd_args):
try:
retval = getattr(mpdclient, mpd_cmd)(*mpd_args)
- except:
+ except Exception, e:
if not mpd_cmd in ['disconnect', 'lsinfo', 'listplaylists']:
- if not suppress_errors:
- print '%s %s' % (strftime("%Y-%m-%d %H:%M:%S"),
- str(sys.exc_info()[1]))
+ logger.error("%s", e)
if mpd_cmd in ['lsinfo', 'list']:
return []
else:
View
25 sonata/pluginsystem.py
@@ -1,6 +1,10 @@
-import os, re, StringIO
-import ConfigParser, pkgutil
+import ConfigParser
+import StringIO
+import logging
+import os
+import pkgutil
+import re
import sonata.plugins
@@ -17,6 +21,7 @@ def find_plugin_dirs():
class Plugin(object):
def __init__(self, path, name, info, load):
+ self.logger = logging.getLogger(__name__)
self.path = path
self.name = name
self._info = info
@@ -71,9 +76,9 @@ def get_features(self, capability):
for f in features.split(', ')]
except KeyboardInterrupt:
raise
- except "Exception":
- print ("Failed to access features in plugin %s." %
- self.name)
+ except:
+ self.logger.exception("Failed to access features in plugin %s.",
+ self.name)
return []
def get_feature(self, module, feature):
@@ -87,7 +92,7 @@ def _get_module(self):
try:
self._module = self._load()
except Exception:
- print "Failed to load plugin %s." % self.name
+ self.logger.exception("Failed to load plugin %s.", self.name)
return None
return self._module
@@ -158,9 +163,9 @@ def find_plugins(self):
if entry.endswith('.py'):
try:
self.load_info(path, entry[:-3])
- except Exception:
- print "Failed to load info:",
- print os.path.join(path, entry)
+ except:
+ self.logger.exception("Failed to load info: %s",
+ os.path.join(path, entry))
def load_info(self, path, name):
f = open(os.path.join(path, name+".py"), "rt")
@@ -187,7 +192,7 @@ def load_info(self, path, name):
self.plugin_infos.append(plugin)
if not info.options('capabilities'):
- print "Warning: No capabilities in plugin %s." % name
+ self.logger.warning("No capabilities in plugin %s.", name)
def import_plugin(self, name):
# XXX load from a .py file - no .pyc etc.
View
12 sonata/scrobbler.py
@@ -11,6 +11,7 @@
self.scrobbler.handle_change_status(False, self.prevsonginfo)
"""
+import logging
import os
import sys
import threading # init, np, post start threads init_thread, do_np, do_post
@@ -24,6 +25,7 @@
class Scrobbler(object):
def __init__(self, config):
+ self.logger = logging.getLogger(__name__)
self.config = config
self.scrob = None
@@ -72,7 +74,7 @@ def init_thread(self):
try:
self.scrob_post.auth()
except Exception, e:
- print "Error authenticating audioscrobbler", e
+ self.logger.error("Error authenticating audioscrobbler: %r", e)
self.scrob_post = None
if self.scrob_post:
self.retrieve_cache()
@@ -173,7 +175,8 @@ def do_np(self, songinfo):
tracknumber,
album)
except:
- print sys.exc_info()[1]
+ self.logger.exception(
+ "Unable to send 'now playing' data to the scrobbler")
time.sleep(10)
def post(self, prevsonginfo):
@@ -199,7 +202,7 @@ def post(self, prevsonginfo):
tracknumber,
album)
except:
- print sys.exc_info()[1]
+ self.logger.critical("Unable to add track to scrobbler")
thread = threading.Thread(target=self.do_post)
thread.setDaemon(True)
@@ -215,7 +218,8 @@ def do_post(self):
try:
self.scrob_post.post()
except audioscrobbler.AudioScrobblerConnectionError, e:
- print e
+ self.logger.exception(
+ "Error while posting data to the scrobbler")
time.sleep(10)
def save_cache(self):
View
7 sonata/ui.py
@@ -1,6 +1,11 @@
+import logging
import gtk, sys, pango
+
+logger = logging.getLogger(__name__)
+
+
def label(text=None, textmn=None, markup=None, x=0, y=0.5, \
wrap=False, select=False, w=-1, h=-1):
# Defaults to left-aligned, vertically centered
@@ -166,7 +171,7 @@ def get_text(self):
try:
return gtk.Entry.get_text(self).decode('utf-8')
except:
- print sys.exc_info()[1]
+ logger.exception("Unable to get text from Gtk widget")
return gtk.Entry.get_text(self).decode('utf-8', 'replace')
def treeview(hint=True, reorder=False, search=True, headers=False):
Please sign in to comment.
Something went wrong with that request. Please try again.