Improve logging messages

This commit is contained in:
Florian Bruhin 2014-06-21 22:40:31 +02:00
parent a3e5a20063
commit a64775a0f9
15 changed files with 63 additions and 48 deletions

View File

@ -253,10 +253,11 @@ class Application(QApplication):
# This means another instance is probably still running and # This means another instance is probably still running and
# didn't remove the file. As we can't write to the same file, # didn't remove the file. As we can't write to the same file,
# we just leave faulthandler as it is and log to stderr. # we just leave faulthandler as it is and log to stderr.
log.init.warn("Empty crash.log detected. This means either " log.init.warn("Empty crash log detected. This means either "
"another instance is running (then ignore this " "another instance is running (then ignore this "
"warning) or the file is lying here because " "warning) or the file is lying here because "
"of some earlier crash (then delete it).") "of some earlier crash (then delete {}).".format(
logname))
self._crashlogfile = None self._crashlogfile = None
else: else:
# There's no log file, so we can use this to display crashes to the # There's no log file, so we can use this to display crashes to the
@ -446,7 +447,8 @@ class Application(QApplication):
if url: if url:
pages.append(url) pages.append(url)
except Exception as e: # pylint: disable=broad-except except Exception as e: # pylint: disable=broad-except
log.init.debug(e) log.destroy.debug("Error while recovering tab: {}: {}".format(
e.__class__.__name__, e))
return pages return pages
def _save_geometry(self): def _save_geometry(self):
@ -486,7 +488,8 @@ class Application(QApplication):
self.shutdown() self.shutdown()
return return
except Exception as e: except Exception as e:
log.destroy.debug(e) log.init.debug("Error while shutting down: {}: {}".format(
e.__class__.__name__, e))
self.quit() self.quit()
return return
@ -498,36 +501,42 @@ class Application(QApplication):
try: try:
pages = self._recover_pages() pages = self._recover_pages()
except Exception as e: except Exception as e:
log.destroy.debug(e) log.destroy.debug("Error while recovering pages: {}: {}".format(
e.__class__.__name__, e))
pages = [] pages = []
try: try:
history = self.mainwindow.status.cmd.history[-5:] history = self.mainwindow.status.cmd.history[-5:]
except Exception as e: except Exception as e:
log.destroy.debug(e) log.destroy.debug("Error while getting history: {}: {}".format(
e.__class__.__name__, e))
history = [] history = []
try: try:
widgets = self.get_all_widgets() widgets = self.get_all_widgets()
except Exception as e: except Exception as e:
log.destroy.debug(e) log.destroy.debug("Error while getting widgets: {}: {}".format(
e.__class__.__name__, e))
widgets = "" widgets = ""
try: try:
objects = self.get_all_objects() objects = self.get_all_objects()
except Exception as e: except Exception as e:
log.destroy.debug(e) log.destroy.debug("Error while getting objects: {}: {}".format(
e.__class__.__name__, e))
objects = "" objects = ""
# Try to shutdown gracefully # Try to shutdown gracefully
try: try:
self.shutdown(do_quit=False) self.shutdown(do_quit=False)
except Exception as e: except Exception as e:
log.destroy.debug(e) log.destroy.debug("Error while shutting down: {}: {}".format(
e.__class__.__name__, e))
try: try:
self.lastWindowClosed.disconnect(self.shutdown) self.lastWindowClosed.disconnect(self.shutdown)
except TypeError as e: except TypeError as e:
log.destroy.warning("Preventing shutdown failed ({}).") log.destroy.debug("Error while preventing shutdown: {}: {}".format(
e.__class__.__name__, e))
QApplication.closeAllWindows() QApplication.closeAllWindows()
self._crashdlg = ExceptionCrashDialog(pages, history, exc, widgets, self._crashdlg = ExceptionCrashDialog(pages, history, exc, widgets,
objects) objects)
@ -575,7 +584,8 @@ class Application(QApplication):
# try: # try:
# argv.remove(page) # argv.remove(page)
# except ValueError as e: # except ValueError as e:
# logger.destroy.debug(e) # logger.destroy.debug("Error while removing page: {}: "
# "{}".format(e.__class__.__name__, e))
# argv = [sys.executable] + argv + pages # argv = [sys.executable] + argv + pages
# log.procs.debug("Running {} with args {} (PYTHONPATH={})".format( # log.procs.debug("Running {} with args {} (PYTHONPATH={})".format(
# sys.executable, argv, pythonpath)) # sys.executable, argv, pythonpath))

View File

@ -348,7 +348,8 @@ class DownloadManager(QObject):
bytes(reply.rawHeader('Content-Disposition'))) bytes(reply.rawHeader('Content-Disposition')))
filename = content_disposition.filename_unsafe filename = content_disposition.filename_unsafe
except UnicodeDecodeError as e: except UnicodeDecodeError as e:
logger.warning(e) logger.warning("Error while getting filename: {}: {}".format(
e.__class__.__name__, e))
filename = None filename = None
else: else:
filename = None filename = None

View File

@ -197,8 +197,8 @@ class BrowserPage(QWebPage):
""" """
try: try:
handler = self._extension_handlers[ext] handler = self._extension_handlers[ext]
except KeyError as e: except KeyError:
log.webview.warning(e) log.webview.warning("Extension {} not supported!".format(ext))
return super().extension(ext, opt, out) return super().extension(ext, opt, out)
return handler(opt, out) return handler(opt, out)

View File

@ -171,7 +171,8 @@ class ConfigManager(QObject):
try: try:
desc = self.sections[sectname].descriptions[optname] desc = self.sections[sectname].descriptions[optname]
except KeyError as e: except KeyError as e:
log.misc.debug(e) log.misc.debug("No description for {}.{}! ({}: {})".format(
sectname, optname, e.__class__.__name__, e))
continue continue
for descline in desc.splitlines(): for descline in desc.splitlines():
lines += wrapper.wrap(descline) lines += wrapper.wrap(descline)

View File

@ -30,7 +30,6 @@ from PyQt5.QtNetwork import QNetworkProxy
import qutebrowser.commands.utils as cmdutils import qutebrowser.commands.utils as cmdutils
from qutebrowser.utils.misc import get_standard_dir from qutebrowser.utils.misc import get_standard_dir
from qutebrowser.utils.log import misc as logger
class ValidationError(ValueError): class ValidationError(ValueError):

View File

@ -107,7 +107,7 @@ class ColorDict(dict):
try: try:
val = super().__getitem__(key) val = super().__getitem__(key)
except KeyError as e: except KeyError as e:
logger.warning(e) logger.warning("No color defined for {}!".format(e))
return '' return ''
if isinstance(val, QColor): if isinstance(val, QColor):
# This could happen when accidentaly declarding something as # This could happen when accidentaly declarding something as

View File

@ -1,4 +1,4 @@
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:)
# Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # Copyright 2014 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# #
@ -63,7 +63,9 @@ class SettingOptionCompletionModel(BaseCompletionModel):
try: try:
desc = sectdata.descriptions[name] desc = sectdata.descriptions[name]
except (KeyError, AttributeError) as e: except (KeyError, AttributeError) as e:
logger.debug(e) logger.debug("Error while getting setting description for "
"{}.{}: {}: {}".format(section, name,
e.__class__.__name__, e))
desc = "" desc = ""
value = config.get(section, name, raw=True) value = config.get(section, name, raw=True)
_valitem, _descitem, miscitem = self.new_item(cat, name, desc, _valitem, _descitem, miscitem = self.new_item(cat, name, desc,
@ -77,8 +79,9 @@ class SettingOptionCompletionModel(BaseCompletionModel):
return return
try: try:
item = self._misc_items[option] item = self._misc_items[option]
except KeyError as e: except KeyError:
logger.debug(e) logger.debug("Couldn't get item {}.{} from model!".format(
section, option))
# changed before init # changed before init
return return
val = config.get(section, option, raw=True) val = config.get(section, option, raw=True)

View File

@ -25,7 +25,6 @@ from PyQt5.QtWidgets import QApplication
import qutebrowser.config.config as config import qutebrowser.config.config as config
from qutebrowser.utils.usertypes import enum from qutebrowser.utils.usertypes import enum
from qutebrowser.utils.log import downloads as logger
from qutebrowser.utils.misc import qt_ensure_valid from qutebrowser.utils.misc import qt_ensure_valid
@ -78,11 +77,7 @@ class DownloadModel(QAbstractListModel):
if index.parent().isValid() or index.column() != 0: if index.parent().isValid() or index.column() != 0:
return QVariant() return QVariant()
try:
item = self.downloadmanager.downloads[index.row()] item = self.downloadmanager.downloads[index.row()]
except IndexError as e:
logger.debug(e)
return QVariant()
if role == Qt.DisplayRole: if role == Qt.DisplayRole:
data = str(item) data = str(item)
elif role == Qt.ForegroundRole: elif role == Qt.ForegroundRole:

View File

@ -86,8 +86,8 @@ class QuteSchemeHandler(SchemeHandler):
request.url().toDisplayString(), path)) request.url().toDisplayString(), path))
try: try:
handler = getattr(QuteHandlers, path) handler = getattr(QuteHandlers, path)
except AttributeError as e: except AttributeError:
logutils.misc.debug(e) logutils.misc.warning("No handler found for {}!".format(path))
data = bytes() data = bytes()
else: else:
data = handler() data = handler()

View File

@ -299,7 +299,8 @@ class Question(QObject):
# FIXME # FIXME
# We seem to get "pyqtSignal must be bound to a QObject, not # We seem to get "pyqtSignal must be bound to a QObject, not
# 'Question' here, which makes no sense at all..." # 'Question' here, which makes no sense at all..."
logger.debug(e) logger.debug("Error while aborting question: {}: {}".format(
e.__class__.__name__, e))
class Timer(QTimer): class Timer(QTimer):

View File

@ -83,7 +83,8 @@ def _git_str():
gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), gitpath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.pardir, os.path.pardir) os.path.pardir, os.path.pardir)
except NameError as e: except NameError as e:
logger.debug(e) logger.debug("Error while getting git path: {}: {}".format(
e.__class__.__name__, e))
else: else:
commit = _git_str_subprocess(gitpath) commit = _git_str_subprocess(gitpath)
if commit is not None: if commit is not None:
@ -126,7 +127,8 @@ def _release_info():
with open(fn, 'r') as f: with open(fn, 'r') as f:
data.append((fn, ''.join(f.readlines()))) data.append((fn, ''.join(f.readlines())))
except IOError as e: except IOError as e:
logger.warn(e) logger.warn("Error while reading {}: {}: {}".format(
fn, e.__class__.__name__, e))
return data return data
@ -147,7 +149,8 @@ def _module_versions():
lines.append('SIP: {}'.format( lines.append('SIP: {}'.format(
sipconfig.Configuration().sip_version_str)) sipconfig.Configuration().sip_version_str))
except (AttributeError, TypeError) as e: except (AttributeError, TypeError) as e:
logger.warn(e) logger.warn("Error while getting SIP version: {}: {}".format(
e.__class__.__name__, e))
lines.append('SIP: ?') lines.append('SIP: ?')
try: try:

View File

@ -122,7 +122,8 @@ class _CrashDialog(QDialog):
self._crash_info.append(("Config", self._crash_info.append(("Config",
config.instance().dump_userconfig())) config.instance().dump_userconfig()))
except AttributeError as e: except AttributeError as e:
self._crash_info.append(("Config", str(e))) self._crash_info.append(("Config", "{}: {}".format(
e.__class__.__name__, e)))
def _format_crash_info(self): def _format_crash_info(self):
"""Format the gathered crash info to be displayed. """Format the gathered crash info to be displayed.
@ -145,7 +146,8 @@ class _CrashDialog(QDialog):
try: try:
url = utils.pastebin(self._txt.toPlainText()) url = utils.pastebin(self._txt.toPlainText())
except (URLError, ValueError) as e: except (URLError, ValueError) as e:
self._url.setText('Error while reporting: {}'.format(str(e))) self._url.setText('Error while reporting: {}: {}'.format(
e.__class__.__name__, e))
return return
self._btn_pastebin.setEnabled(False) self._btn_pastebin.setEnabled(False)
self._url.setText("Reported to: <a href='{}'>{}</a>".format(url, url)) self._url.setText("Reported to: <a href='{}'>{}</a>".format(url, url))
@ -218,7 +220,8 @@ class ExceptionCrashDialog(_CrashDialog):
self._crash_info.append(("Debug log", self._crash_info.append(("Debug log",
logutils.ram_handler.dump_log())) logutils.ram_handler.dump_log()))
except AttributeError as e: except AttributeError as e:
self._crash_info.append(("Debug log", str(e))) self._crash_info.append(("Debug log", "{}: {}".format(
e.__class__.__name__, e)))
class FatalCrashDialog(_CrashDialog): class FatalCrashDialog(_CrashDialog):

View File

@ -60,15 +60,18 @@ class MainWindow(QWidget):
geom = b64decode(stateconf['geometry']['mainwindow'], geom = b64decode(stateconf['geometry']['mainwindow'],
validate=True) validate=True)
except (KeyError, binascii.Error) as e: except (KeyError, binascii.Error) as e:
logger.warn(e) logger.warn("Error while reading geometry: {}: {}".format(
e.__class__.__name__, e))
self._set_default_geometry() self._set_default_geometry()
else: else:
try: try:
ok = self.restoreGeometry(geom) ok = self.restoreGeometry(geom)
except KeyError: except KeyError:
logger.warn(e) logger.warn("Error while restoring geometry: {}: {}".format(
e.__class__.__name__, e))
self._set_default_geometry() self._set_default_geometry()
if not ok: if not ok:
logger.warn("Error while restoring geometry.")
self._set_default_geometry() self._set_default_geometry()
self._vbox = QVBoxLayout(self) self._vbox = QVBoxLayout(self)

View File

@ -135,9 +135,8 @@ class TabbedBrowser(TabWidget):
""" """
try: try:
self._tabs.remove(tab) self._tabs.remove(tab)
except ValueError as e: except ValueError:
log.destroy.exception("tab {} could not be removed ({})".format( log.destroy.exception("tab {} could not be removed")
tab, e))
log.destroy.debug("Tabs after removing: {}".format(self._tabs)) log.destroy.debug("Tabs after removing: {}".format(self._tabs))
if not self._tabs: # all tabs shut down if not self._tabs: # all tabs shut down
log.destroy.debug("Tab shutdown complete.") log.destroy.debug("Tab shutdown complete.")
@ -201,7 +200,8 @@ class TabbedBrowser(TabWidget):
try: try:
self.currentChanged.disconnect() self.currentChanged.disconnect()
except TypeError as e: except TypeError as e:
log.destroy.debug(e) log.destroy.debug("Error while shutting down tabs: {}: {}".format(
e.__class__.__name__, e))
tabcount = self.count() tabcount = self.count()
if tabcount == 0: if tabcount == 0:
log.destroy.debug("No tabs -> shutdown complete") log.destroy.debug("No tabs -> shutdown complete")

View File

@ -24,7 +24,6 @@ from PyQt5.QtWidgets import QTabWidget, QTabBar, QSizePolicy
from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtGui import QIcon, QPixmap
import qutebrowser.config.config as config import qutebrowser.config.config as config
import qutebrowser.utils.log as log
from qutebrowser.config.style import set_register_stylesheet from qutebrowser.config.style import set_register_stylesheet
from qutebrowser.utils.style import Style from qutebrowser.utils.style import Style
@ -108,11 +107,8 @@ class TabWidget(QTabWidget):
self.setUsesScrollButtons(config.get('tabbar', 'scroll-buttons')) self.setUsesScrollButtons(config.get('tabbar', 'scroll-buttons'))
posstr = config.get('tabbar', 'position') posstr = config.get('tabbar', 'position')
selstr = config.get('tabbar', 'select-on-remove') selstr = config.get('tabbar', 'select-on-remove')
try:
self.setTabPosition(position_conv[posstr]) self.setTabPosition(position_conv[posstr])
self.tabBar().setSelectionBehaviorOnRemove(select_conv[selstr]) self.tabBar().setSelectionBehaviorOnRemove(select_conv[selstr])
except KeyError as e:
log.init.warn(e)
@pyqtSlot(str, str) @pyqtSlot(str, str)
def on_config_changed(self, section, _option): def on_config_changed(self, section, _option):