Cleaned up the logging system a bit.
authorPaweł Paprota <ppawel@fastmail.fm>
Sat, 29 Mar 2008 12:33:11 +0000 (29 13:33 +0100)
committerPaweł Paprota <ppawel@fastmail.fm>
Sun, 20 Apr 2008 16:45:48 +0000 (20 18:45 +0200)
scripts/straw-local
straw/Application.py
straw/ItemList.py
straw/MessageManager.py
straw/error.py
straw/feedfinder.py
straw/helpers.py

index 5a7e467..cb74e8e 100755 (executable)
@@ -78,6 +78,9 @@ def setup():
     m.STRAW_HOME = "http://www.gnome.org/projects/straw"
     m.STRAW_DATA_DIR = os.path.join(get_root(), "data")
 
+    from straw import error
+    error.setup_log()
+
 def tear_down():
     # remove created compiled files
     import dircache
@@ -88,8 +91,6 @@ def tear_down():
             filepath = os.path.join(d, fn)
             if filepath.endswith(".pyc"):
                 os.remove(filepath)
-    print '.. exiting.'
-
 
 def parse_args():
     from optparse import OptionParser
index 6da19a6..23eacd8 100644 (file)
@@ -46,6 +46,8 @@ import straw.defs
 import time
 pygtk.require('2.0')
 
+log = error.get_logger()
+
 class StatusPresenter(MVP.BasicPresenter):
     def _initialize(self):
         self._mmgr = get_status_manager()
@@ -89,7 +91,7 @@ class ErrorPresenter:
 
         if text:
             t = "\n".join(text)
-            self._tooltips.set_tip(self._widget,t,t)
+            self._tooltips.set_tip(self._widget, t, t)
             self._tooltips.enable()
             self._widget.show()
         else:
@@ -219,7 +221,7 @@ class ApplicationPresenter(MVP.BasicPresenter):
         self._offline_presenter = OfflineToggle(widget_tree.get_widget('offline_toggle'))
 
         self._status_presenter = StatusPresenter(view = widget_tree.get_widget("main_statusbar"))
-#        self._find_presenter = FindPresenter(view=FindView(widget_tree.get_widget("find_vbox")))
+        #self._find_presenter = FindPresenter(view=FindView(widget_tree.get_widget("find_vbox")))
 
     def set_current_item(self, item):
         self._current_item = item
@@ -449,7 +451,7 @@ class ApplicationPresenter(MVP.BasicPresenter):
         model = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_PYOBJECT)
         combobox = gtk.ComboBox(model)
         celltitle = gtk.CellRendererText()
-        combobox.pack_start(celltitle,False)
+        combobox.pack_start(celltitle, False)
         combobox.add_attribute(celltitle, 'text', 0)
 
         for category in category_list:
@@ -458,17 +460,17 @@ class ApplicationPresenter(MVP.BasicPresenter):
 
         combobox.set_active(0)
         label = gtk.Label(extra_widget_title)
-        label.set_alignment(1.0,0.5)
+        label.set_alignment(1.0, 0.5)
         hbox = gtk.HBox(spacing=6)
-        hbox.pack_start(label,True,True,0)
-        hbox.pack_end(combobox,False,False,0)
+        hbox.pack_start(label, True, True, 0)
+        hbox.pack_end(combobox, False, False, 0)
         hbox.show_all()
 
         dialog.set_extra_widget(hbox)
         return (dialog, combobox)
 
     def import_subscriptions(self, parent):
-        (dialog,combobox) = self._setup_filechooser_dialog(_("Import Subscriptions"),
+        (dialog, combobox) = self._setup_filechooser_dialog(_("Import Subscriptions"),
                                                              gtk.FILE_CHOOSER_ACTION_OPEN,
                                                              _("Add new subscriptions in:"))
         ffilter = gtk.FileFilter()
@@ -487,7 +489,7 @@ class ApplicationPresenter(MVP.BasicPresenter):
         dialog.destroy()
 
     def export_subscriptions(self, parent):
-        (dialog,combobox) = self._setup_filechooser_dialog(_("Export Subscriptions"),
+        (dialog, combobox) = self._setup_filechooser_dialog(_("Export Subscriptions"),
                                                              gtk.FILE_CHOOSER_ACTION_SAVE,
                                                              _("Select category to export:"))
         def selection_changed(widget, dialog):
@@ -532,7 +534,7 @@ class ApplicationView(MVP.WidgetView):
             # overwrite the default size if we use set_default_size.
             #self._widget.move(Config.get(OPTION_WINDOW_LEFT), Config.get(OPTION_WINDOW_TOP))
             #self._widget.resize(Config.get(OPTION_WINDOW_SIZE_W), Config.get(OPTION_WINDOW_SIZE_H))
-            self._widget.window.move_resize(Config.get(OPTION_WINDOW_LEFT), Config.get(OPTION_WINDOW_TOP), 
+            self._widget.window.move_resize(Config.get(OPTION_WINDOW_LEFT), Config.get(OPTION_WINDOW_TOP),
                                             Config.get(OPTION_WINDOW_SIZE_W), Config.get(OPTION_WINDOW_SIZE_H))
         self.mmp = widget_tree.get_widget('main_main_pane')
         self.msp = widget_tree.get_widget('main_sub_pane')
@@ -575,7 +577,7 @@ class ApplicationView(MVP.WidgetView):
                          'urfeeds': urfeeds,
                          'fstring' : sfeeds}
         title = _('%(uritems)d unread in %(urfeeds)d %(fstring)s') % item_feed_map
-        self._widget.set_title( title + " - %s" % straw.defs.PACKAGE)
+        self._widget.set_title(title + " - %s" % straw.defs.PACKAGE)
 
     # We have a separate accelerator group for the unmodified and
     # shifted accelerators, that is, stuff like space, N, P, etc. This
@@ -741,8 +743,7 @@ class ApplicationView(MVP.WidgetView):
 class Application:
     def __init__(self):
         gnome.program_init(straw.defs.PACKAGE, straw.defs.VERSION)
-        
-        error.setup_log()
+
         # initialize threading and environment
         gobject.threads_init()
 
@@ -752,7 +753,7 @@ class Application:
         image = gtk.Image()
         iconfile = os.path.normpath(straw.defs.STRAW_DATA_DIR + "/straw.png")
         pixbuf = gtk.gdk.pixbuf_new_from_file(iconfile)
-        scaled_buf = pixbuf.scale_simple(16,16,gtk.gdk.INTERP_BILINEAR)
+        scaled_buf = pixbuf.scale_simple(16, 16, gtk.gdk.INTERP_BILINEAR)
         image.set_from_pixbuf(scaled_buf)
         try:
             self.tray = gtk.status_icon_new_from_pixbuf(scaled_buf)
@@ -767,7 +768,7 @@ class Application:
             self._eventbox.connect("drag-data-received", self._on_drag_data_received)
             self._eventbox.drag_dest_set(
                 gtk.DEST_DEFAULT_ALL,
-                [('_NETSCAPE_URL', 0, 0),('text/uri-list ', 0, 1),('x-url/http', 0, 2)],
+                [('_NETSCAPE_URL', 0, 0), ('text/uri-list ', 0, 1), ('x-url/http', 0, 2)],
                 gtk.gdk.ACTION_COPY | gtk.gdk.ACTION_MOVE)
             self._eventbox.add(image)
             self.tray.show_all()
@@ -790,17 +791,17 @@ class Application:
 
         #ImageCache.initialize()
 
-        xml = gtk.glade.XML(os.path.join(straw.defs.STRAW_DATA_DIR,'straw.glade'), "straw_main", gettext.textdomain())
+        xml = gtk.glade.XML(os.path.join(straw.defs.STRAW_DATA_DIR, 'straw.glade'), "straw_main", gettext.textdomain())
         window = xml.get_widget('straw_main')
         self._main_presenter = ApplicationPresenter(view = ApplicationView(window))
         self._main_presenter.view.present()
         
-        self._main_presenter.view._widget.window.move_resize(Config.get(OPTION_WINDOW_LEFT), Config.get(OPTION_WINDOW_TOP), 
+        self._main_presenter.view._widget.window.move_resize(Config.get(OPTION_WINDOW_LEFT), Config.get(OPTION_WINDOW_TOP),
                                             Config.get(OPTION_WINDOW_SIZE_W), Config.get(OPTION_WINDOW_SIZE_H))
 
         #PollManager.get_instance().start_polling_loop()
         # set the default icon for the windows
-        iconfile = os.path.join(straw.defs.STRAW_DATA_DIR,"straw.png")
+        iconfile = os.path.join(straw.defs.STRAW_DATA_DIR, "straw.png")
         gtk.window_set_default_icon(gtk.gdk.pixbuf_new_from_file(iconfile))
 
         start_services()
@@ -811,7 +812,7 @@ class Application:
         gtk.main()
         gtk.gdk.threads_leave()
 
-    def _update(self,flist):
+    def _update(self, flist):
         uritems = urfeeds = 0
         for ur in [f.number_of_unread for f in flist.flatten_list()]:
             if ur:
index 46285fb..6193de9 100644 (file)
@@ -289,16 +289,14 @@ class ItemListPresenter(MVP.BasicPresenter):
             items = ItemManager.get_feed_items(node.node.id)
         elif node.node.type == "C":
             items = ItemManager.get_category_items(node.node.id)
-        
-        self.view._widget.set_model(None)
 
+        self.view._widget.set_model(None)
         self.model.populate(items)
-
         self.view._widget.set_model(self._model.model)
-        
+
         if not len(self.model.model): return
-        if not self.view.select_next_unread_item():
-            self.view.select_first_item()
+        #if not self.view.select_next_unread_item():
+        #    self.view.select_first_item()
 
     def flatten(self, sequence):
         ''' python cookbook recipe 4.6 '''
index fe58f1a..ad02654 100644 (file)
@@ -17,15 +17,16 @@ You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA 02111-1307, USA. """
 
-import logging
+from dbus import DBusException
+from subscribe import subscribe_show
+import Config
 import dbus
-import dbus.service
 import dbus.glib
-from dbus import DBusException
+import dbus.service
+import error
 import gobject
-import Config
 
-from subscribe import subscribe_show
+log = error.get_logger()
 
 # Based on the values from NetworkManager/include/NetworkManager.h
 # We only care about CONNECTED and DISCONNECTED at the moment.
@@ -79,12 +80,12 @@ def start_services():
         nm_interface.connect_to_signal('DeviceNowActive', nl.active_cb)
         nm_interface.connect_to_signal('DeviceNoLongerActive', nl.inactive_cb)
     except DBusException, e:
-        logging.info(_("Unable to find NetworkManager service: [%s]" % str(e)))
+        log.info(_("Unable to find NetworkManager service: [%s]" % str(e)))
 
 class StatusMessageManager(gobject.GObject):
 
     __gsignals__ = {
-        'changed' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,())
+        'changed' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ())
         }
 
     def __init__(self):
index 7b5a16f..cb528d0 100644 (file)
@@ -18,20 +18,19 @@ You should have received a copy of the GNU General Public License along with
 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 Place - Suite 330, Boston, MA 02111-1307, USA. """
 
-import sys
-import traceback
-import pprint
 from StringIO import StringIO
 import logging
+import pprint
+import sys
+import traceback
 
 stream = sys.stderr
 
 def setup_log():
     logging.basicConfig(level=logging.DEBUG,
                     format='%(asctime)s %(levelname)-8s %(message)s',
-                    datefmt='%m-%d %H:%M',
                     filename='straw.log',
-                    filemode='a')
+                    filemode='w')
 
     console = logging.StreamHandler()
     console.setLevel(logging.DEBUG)
@@ -39,6 +38,10 @@ def setup_log():
     console.setFormatter(formatter)
     logging.getLogger('').addHandler(console)
 
+def get_logger():
+    # TODO: introduce hierarchical loggers
+    return logging.getLogger("")
+
 def debug(msg, *args, **kwargs):
     logging.debug(msg)
 
index 39bf916..161127d 100644 (file)
@@ -44,11 +44,12 @@ __license__ = "Python"
 __credits__ = """Abe Fettig for a patch to sort Syndic8 feeds by popularity
 Also Jason Diamond, Brian Lalor for bug reporting and patches"""
 
-_debug = 1
+import error
+import sgmllib, urlparse, re, sys, robotparser
+import threading
 
-import sgmllib, urllib, urlparse, re, sys, robotparser
+log = error.get_logger()
 
-import threading
 class TimeoutError(Exception): pass
 def timelimit(timeout):
     """borrowed from web.py"""
@@ -94,18 +95,16 @@ if not dict:
         return rc
     
 def _debuglog(message):
-    if _debug: print message
-    
+    log.debug(message)
+
 class URLGatekeeper:
     """a class to track robots.txt rules across multiple servers"""
     def __init__(self):
         self.rpcache = {} # a dictionary of RobotFileParser objects, by domain
-        self.urlopener = urllib.FancyURLopener()
-        self.urlopener.version = "feedfinder/" + __version__ + " " + self.urlopener.version + " +http://www.aaronsw.com/2002/feedfinder/"
-        _debuglog(self.urlopener.version)
-        self.urlopener.addheaders = [('User-agent', self.urlopener.version)]
-        robotparser.URLopener.version = self.urlopener.version
-        robotparser.URLopener.addheaders = self.urlopener.addheaders
+        self.version = "feedfinder/" + __version__ + " +http://www.aaronsw.com/2002/feedfinder/"
+        self.addheaders = [('User-agent', self.version)]
+        robotparser.URLopener.version = self.version
+        robotparser.URLopener.addheaders = self.addheaders
         
     def _getrp(self, url):
         protocol, domain = urlparse.urlparse(url)[:2]
@@ -124,7 +123,7 @@ class URLGatekeeper:
 
     def can_fetch(self, url):
         rp = self._getrp(url)
-        allow = rp.can_fetch(self.urlopener.version, url)
+        allow = rp.can_fetch(self.version, url)
         _debuglog("gatekeeper of %s says %s" % (url, allow))
         return allow
 
@@ -146,7 +145,6 @@ class URLGatekeeper:
                 resp, content = h.request(url, "GET")
 
             return content
-            #return self.urlopener.open(url).read()
         except Exception, e:
             _debuglog(e)
             return ''
index 366dc90..0ab92d6 100644 (file)
@@ -34,6 +34,8 @@ import straw
 import urllib, string, urlparse
 import xml
 
+log = error.get_logger()
+
 class UIFactory(object):
     _shared_state = {}
     manager = None
@@ -63,7 +65,7 @@ class UIFactory(object):
 
     def __init__(self, name):
         if not self.manager:
-            print 'initializing ui manager'
+            log.info("Initializing UI manager")
             self.action_groups = {}
             self.manager = gtk.UIManager()
             action_group = gtk.ActionGroup(name)
@@ -246,6 +248,7 @@ def convert_entities(text):
 def complete_url(url, feed_location):
     #print "---- COMPLETING %s WITH %s" % (url, feed_location)
     url = urllib.quote(url, safe=string.punctuation)
+
     if urlparse.urlparse(url)[0] == '':
         return urlparse.urljoin(feed_location, url)
     else: