Permalink
Browse files

Add support for logging module

Merge branch 'logging-support' into integration
  • Loading branch information...
2 parents c839888 + 0695b3e commit 3b4c7e15c24fbafbadc1e2ed99aa32e3db5a7fe1 @multani committed Dec 28, 2011
Showing with 162 additions and 75 deletions.
  1. +0 −1 TODO
  2. +12 −6 sonata/audioscrobbler.py
  3. +25 −8 sonata/cli.py
  4. +18 −10 sonata/dbus_plugin.py
  5. +4 −2 sonata/info.py
  6. +29 −16 sonata/launcher.py
  7. +10 −2 sonata/lyricwiki.py
  8. +7 −5 sonata/main.py
  9. +5 −1 sonata/misc.py
  10. +18 −8 sonata/mpdhelper.py
  11. +15 −10 sonata/pluginsystem.py
  12. +5 −1 sonata/rhapsodycovers.py
  13. +8 −4 sonata/scrobbler.py
  14. +6 −1 sonata/ui.py
View
1 TODO
@@ -55,7 +55,6 @@ clean-up
- write automated tests
- refactor code into parts that can be tested
use the logging module:
- - add verbose and debug logging modes
- log to file if not running on console
exceptions:
- add class restrictions to most "except:" clauses
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
@@ -62,9 +64,19 @@ def parse(self, argv):
help=_("start app visible (requires systray)"))
parser.add_option("--profile", dest="profile", metavar="NUM",
help=_("start with profile NUM"), type=int)
+ parser.add_option("-v", "--verbose", dest="log_level",
+ action="append_const", const=-10,
+ help=_("Increase log verbosity"))
+ parser.add_option("-q", "--quiet", dest="log_level",
+ action="append_const", const=10,
+ help=_("Decrease log verbosity"))
+ parser.set_defaults(log_level=[logging.root.level])
options, self.cmds = parser.parse_args(argv[1:])
+ # Update default log level
+ logging.root.setLevel(sum(options.log_level))
+
if options.toggle:
options.start_visibility = True
if options.popup or options.fullscreen and options.start_visibility is None:
@@ -81,7 +93,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 +117,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 +139,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 +163,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
Oops, something went wrong.

0 comments on commit 3b4c7e1

Please sign in to comment.