Permalink
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...
multani committed Dec 27, 2011
1 parent c839888 commit 37cfefc2bebfa514bfcb71fe371e76d6874d2b74
Showing with 134 additions and 73 deletions.
  1. +12 −6 sonata/audioscrobbler.py
  2. +15 −8 sonata/cli.py
  3. +18 −10 sonata/dbus_plugin.py
  4. +4 −2 sonata/info.py
  5. +29 −16 sonata/launcher.py
  6. +4 −2 sonata/lyricwiki.py
  7. +7 −5 sonata/main.py
  8. +5 −1 sonata/misc.py
  9. +11 −8 sonata/mpdhelper.py
  10. +15 −10 sonata/pluginsystem.py
  11. +8 −4 sonata/scrobbler.py
  12. +6 −1 sonata/ui.py
View
@@ -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
@@ -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
@@ -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
@@ -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
@@ -24,36 +24,48 @@
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():
"""Main entry point of Sonata"""
# 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
@@ -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
@@ -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
Oops, something went wrong.

0 comments on commit 37cfefc

Please sign in to comment.